【发布时间】:2019-12-28 15:37:05
【问题描述】:
在服务器渲染代理工作正常。请求将发送至 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>
【问题讨论】:
-
你需要做的第一件事,就是理解vue的生命周期。查看文档:vuejs.org/v2/guide/instance.html。在您的代码中,您有以下代码: process.browser.... 这意味着您将等待页面加载,然后再运行您的请求。所以这是一种错误的方式,因为您需要在创建组件之前获取任何数据,并在创建组件后设置要使用的数据属性。你不需要检查 process.browser 来满足你的 axios 请求。
-
你可以提高能力的另一件事是了解 vuex。因为,在 vuex 中,你有简单的状态,并且有动作、getter 和很多好东西来管理你的状态。这是正确的方法,也是一种非常简洁和专业的方法。查看文档:vuex.vuejs.org
标签: javascript vue.js nuxt.js