简体   繁体   English

为什么代理在浏览器中不起作用(NuxtJS+Axios)?

[英]Why Proxy not working in browser (NuxtJS+Axios)?

In server rendering Proxy is working fine.在服务器渲染代理工作正常。 Request is going to custom-server.com/v1/places.请求将发送至 custom-server.com/v1/places。 But in browser request is going to current-domain.com/api/places但是在浏览器中请求将转到 current-domain.com/api/places

Why it is not working in browser?为什么它在浏览器中不起作用? Proxy working only in server side?代理仅在服务器端工作? Please, help.请帮忙。

I have NuxtJS config:我有 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,
        },
    },
}

My component:我的组件:

<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>

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

Need to following change of Given code and need to understand the vuejs/Nuxtjs lifecyle需要跟随给定代码的变化并且需要了解 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' : ""
            },
        },
    },
}

and the given code inside created() hook is need to change another life cycle maybe.并且 created() 钩子中的给定代码可能需要更改另一个生命周期。 or need to move inside method() or as per need your requirements.或需要在 method() 内部移动或根据您的要求移动。

adding prefix to axios in nuxt.config.js helped menuxt.config.js为 axios 添加prefix对我有帮助

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM