In server rendering Proxy is working fine. Request is going to custom-server.com/v1/places. But in browser request is going to current-domain.com/api/places
Why it is not working in browser? Proxy working only in server side? Please, help.
I have NuxtJS config:
require('dotenv').config();
export default {
mode: 'universal',
buildModules: [],
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy',
['@nuxtjs/dotenv', { systemvars: true }],
],
axios: {
proxy: true,
credentials: true,
},
proxy: {
'/api': {
target: "http://custom-server.com",
pathRewrite: {
'^/api' : "/v1"
},
changeOrigin: true,
},
},
}
My component:
<script>
export default {
data() {
return{
placesServer:false,
placesBrowser:false,
}
},
async asyncData ({ $axios }) {
// Here is all is finelet response = await $axios.get("/api/places");
return {
placesServer:response.data,
};
},
created(){
if (process.browser){
// Here is not working =(this.$axios.get("/api/places").then((response)=>{
this.placesBrowser = response.data;
});
}else{
// Here is working fine!this.$axios.get("/api/places").then((response)=>{
this.placesBrowser = response.data;
});
}
}
}
</script>
It looks like you are trying to use the /api proxy on the client-side. However, the proxy option in Nuxt.js only works on the server-side, which is why it is working in the asyncData method but not on the client-side.
To make a request to the custom-server.com server from the client-side, you can use the baseURL option in the axios module configuration to set the base URL for all your axios requests:
axios: { baseURL: 'http://custom-server.com/v1', },
Then, you can make requests to the custom server using the $axios instance, like this:
this.$axios.get('/places').then(response => { this.placesBrowser = response.data })
Alternatively, you can make requests directly to the custom server using the full URL:
this.$axios.get('http://custom-server.com/v1/places').then(response => { this.placesBrowser = response.data })