代理 `changeOrigin` 设置似乎不起作用

Ege*_*soz 6 vue.js vue-cli

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

我按照Vue CLI 文档中的 devServer.proxy 说明向我的vue.config.js. 我还按照http-proxy-middleware 库的说明来补充选项:

module.exports = {
  lintOnSave: true,
  outputDir: '../priv/static/',
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:4000',
        changeOrigin: true,
        ws: true,
      },
    },
  },
}; 
Run Code Online (Sandbox Code Playgroud)

我的理解是该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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

vto*_*osh 10

我遇到了基本上相同的问题,最终对我有用的是手动覆盖标题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");
        },
      },
    },
  },
}; 
Run Code Online (Sandbox Code Playgroud)

  • 似乎`changeOrigin: true`仅适用于`GET`请求,而对于其他`POST、PATCH等`,需要强制使用`onProxyReq:`函数...... (3认同)

wat*_*k47 7

这是我的 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");
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    });
}
Run Code Online (Sandbox Code Playgroud)

API请求:

import {postRequest} from "../http";

const category = {
    store(params) {
        return postRequest("/api/admin/category", params);
    }
}

export default category;
Run Code Online (Sandbox Code Playgroud)

原则: