I am working on a nuxt application which uses axios
to get data from an API on the backend using asyncData
. I also have the @nuxtjs/proxy
module added as a dependency which proxies all of my API calls.
Whenever I navigate to the page using a link on the client side, the proxy works as intended and removes the /api/
prefix from the path before sending the request to the backend API.
Example:
- Client requests:
/api/data
- Proxy strips
/api/
from request- Resulting path to api:
http://example.com/data
However, the issue I am running into is on page refreshes. The proxy module is failing to strip /api/
from the path resulting in a path that does not exist on the api
Example:
- Desired path:
http://example.com/data
- Path on refresh:
http://example.com/api/data
Here is my simplified nuxt.config.js
:
export default {
components: true,
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy',
],
axios: {
proxy: true,
},
proxy: {
'/api/': { target: process.env.API_URL, pathRewrite: { '^/api/': '' } },
}
}
Here is a simplified verson of my .Vue
page:
<template>
<div>This is a vue Page</div>
</template>
<script>
export default {
name: 'VuePage',
async asyncData({ error, query, $axios }) {
try {
const { data } = await $axios.get('/api/data', { params: query });
return {
data,
};
} catch (err) {
error({
statusCode: err.response.status,
message: err.response.data.message,
});
}
},
};
</script>
I have already checked out some other question on StackOverflow with no good solid answer.
A similar question asked was, Nuxt: Proxy VS Async data VS Reload page
The question was marked as answered with no explanation given of the how the problem was solved.
I was able to find a workaround in the form of a plugin that appears to resolve the issue.
The plugin is based off a reddit post by user wiked03
and is designed to strip /api/
from the request
Create a folder in your project root called plugins
and create a file called axios.js
Add this code to ./plugins/axios.js
// ./plugins/axios.js
export default function ({ $axios }) {
$axios.onRequest((config) => {
if (process.server) {
config.url = config.url.replace('/api/', process.env.API_URL)
}
})
}
Locate your your nuxt config file nuxt.config.js
and edit it as follows:
// ./nuxt.config.js
export default {
// ~~~~ Some Configs ~~~~ //
plugins: ['~/plugins/axios.js'],
}
Source: