【问题标题】:Why Proxy not working in browser (NuxtJS+Axios)?为什么代理在浏览器中不起作用(NuxtJS+Axios)?
【发布时间】: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


【解决方案1】:

如果您的 API URL 是 =http://custom-server.com/api/v1/api/places

需要跟随 Given 代码的变化,需要了解 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() 或根据需要移动。

【讨论】:

    【解决方案2】:

    prefix 添加到nuxt.config.js 中的axios 对我有帮助

    axios: {
     proxy: true,
     credentials: true,
     prefix: '/api/'
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 1970-01-01
      • 2021-10-18
      • 2011-04-30
      • 2022-06-14
      • 2014-09-26
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      相关资源
      最近更新 更多