[英]Why Proxy not working in browser (NuxtJS+Axios)?
在服务器渲染代理工作正常。 请求将发送至 custom-server.com/v1/places。 但是在浏览器中请求将转到 current-domain.com/api/places
为什么它在浏览器中不起作用? 代理仅在服务器端工作? 请帮忙。
我有 NuxtJS 配置:
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,
},
},
}
我的组件:
<script>
export default {
data() {
return{
placesServer:false,
placesBrowser:false,
}
},
async asyncData ({ $axios }) {
// Here is all is fine
let 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>
如果您的 API URL 是 = http://custom-server.com/api/v1/api/places
需要跟随给定代码的变化并且需要了解 vuejs/Nuxtjs 生命周期
export default {
mode: 'universal',
buildModules: [],
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy',
['@nuxtjs/dotenv', { systemvars: true }],
],
axios: {
proxy: true,
},
proxy: {
'/api': {
target: "http://custom-server.com",
pathRewrite: {
'^/api' : ""
},
},
},
}
并且 created() 钩子中的给定代码可能需要更改另一个生命周期。 或需要在 method() 内部移动或根据您的要求移动。
在nuxt.config.js
为 axios 添加prefix
对我有帮助
axios: {
proxy: true,
credentials: true,
prefix: '/api/'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.