【问题标题】:Proxy `changeOrigin` setting doesn't seem to work代理“changeOrigin”设置似乎不起作用
【发布时间】:2019-01-19 00:04:20
【问题描述】:

我正在使用 Vue CLI 3.0.0 (rc.10) 并且并排运行两台服务器(后端服务器和 WDS)。

我关注the devServer.proxy instructions on the Vue CLI documentation 为我的vue.config.js 添加了代理选项。我也跟着the instructions for the http-proxy-middleware library补充了选项:

module.exports = {
  lintOnSave: true,
  outputDir: '../priv/static/',
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:4000',
        changeOrigin: true,
        ws: true,
      },
    },
  },
}; 

我的理解是changeOrigin: true选项需要将请求上的Origin标头动态更改为“http://localhost:4000”。但是,来自我的应用程序的请求仍然从 http://localhost:8080 发送,它们触发了 CORS 阻塞:

Request URL: http://localhost:4000/api/form
Request Method: OPTIONS
Status Code: 404 Not Found
Remote Address: 127.0.0.1:4000
Host: localhost:4000
Origin: http://localhost:8080 <-- PROBLEM

我做错了什么?

【问题讨论】:

    标签: vue.js vue-cli


    【解决方案1】:

    我遇到了基本相同的问题,最终对我有用的是手动覆盖 Origin 标头,如下所示:

    module.exports = {
      lintOnSave: true,
      outputDir: '../priv/static/',
      devServer: {
        proxy: {
          '/api': {
            target: 'http://localhost:4000',
            changeOrigin: true,
            ws: true,
            onProxyReq: function(request) {
              request.setHeader("origin", "http://localhost:4000");
            },
          },
        },
      },
    }; 
    

    【讨论】:

    • 看来changeOrigin: true只适用于GET请求,而对于其他POST, PATCH, etc,需要强制使用onProxyReq:函数...
    【解决方案2】:

    这是我的 vue.config.js,对我来说很好用:

    module.exports = {
        baseUrl: './',
        assetsDir: 'static',
        productionSourceMap: false,
        configureWebpack: {
            devServer: {
                headers: { "Access-Control-Allow-Origin": "*" }
            }
        },
        devServer: {
            proxy: {
                '/api': {
                    target: 'http://127.0.0.1:3333/api/',
                    changeOrigin: false,
                    secure: false,
                    pathRewrite: {
                        '^/api': ''
                    },
                    onProxyReq: function (request) {
                        request.setHeader("origin", "http://127.0.0.1:3333");
                    }
                }
            }
        }
    }
    

    axios.config.js:

    import axios from 'axios';
    import { Message, Loading } from 'element-ui'
    
    // axios.defaults.baseURL = "http://127.0.0.1:3333/";
    
    
    axios.defaults.timeout = 5 * 1000
    
    // axios.defaults.withCredentials = true
    
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    
    let loading = null;
    
    function startLoading() {
        loading = Loading.service({
            lock: true,
            text: 'loading....',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.8)'
        })
    }
    
    function endLoading() {
        loading.close()
    }
    
    axios.interceptors.request.use(
        (confing) => {
            startLoading()
    
            // if (localStorage.eToken) {
            //     confing.headers.Authorization = localStorage.eToken
            // }
            return confing
        },
        (error) => {
            console.log("request error: ", error)
            return Promise.reject(error)
        }
    )
    
    
    axios.interceptors.response.use(
        (response) => {
            endLoading()
            return response.data;
        },
        (error) => {
    
            console.log("response error: ", error);
    
            endLoading()
    
    
            return Promise.reject(error)
        }
    )
    
    
    export const postRequest = (url, params) => {
        return axios({
            method: 'post',
            url: url,
            data: params,
            transformRequest: [function (data) {
                let ret = ''
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                return ret
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        });
    }
    
    
    export const uploadFileRequest = (url, params) => {
        return axios({
            method: 'post',
            url: url,
            data: params,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
    }
    
    export const getRequest = (url) => {
        return axios({
            method: 'get',
            url: url
        });
    }
    
    
    export const putRequest = (url, params) => {
        return axios({
            method: 'put',
            url: url,
            data: params,
            transformRequest: [function (data) {
                let ret = ''
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                return ret
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        });
    }
    
    export const deleteRequest = (url) => {
        return axios({
            method: 'delete',
            url: url
        });
    }
    

    api 请求:

    import {postRequest} from "../http";
    
    const category = {
        store(params) {
            return postRequest("/api/admin/category", params);
        }
    }
    
    export default category;
    

    原理:

    【讨论】:

      【解决方案3】:

      changeOrigin 只更改host 标头!!!

      查看文档http-proxy-middleware#http-proxy-options

      option.changeOrigin:true/false,默认值:false - 将主机头的来源更改为目标 URL

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-23
        • 1970-01-01
        • 2019-06-19
        • 2017-12-22
        • 2015-12-15
        • 1970-01-01
        相关资源
        最近更新 更多