foreword
The vue2 project involves cross-domain issues. After a copy operation on the Internet, the result is still not working. There is no way, I can only come to my own understanding!
configuration
Create a new file in the root directory of the project vue.config.js
For example: proxy local requests tohttp://123456.com
module.exports = {
publicPath: process.env.NODE_ENV === "production" ? "./" : "/",
devServer: {
host: "localhost",
port: 1001, // 端口号
https: false, // https:{type:Boolean}
open: true, //配置自动启动浏览器
// 配置多个代理
proxy: {
"/api": {
target: "http://123456.com",
// ws: true, // 是否启用websockets
changeOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite: {
"^/api": "/aaa/api/ccc", // 路径重写
},
},
},
},
};
The interface prefix of the project is /aaa/api/ccc
, such as obtaining user information /aaa/api/ccc/getUser
, setting the request prefix in axios
baseURL: "/api", //本地
// baseURL: "/aaa/api/ccc", // 测试服
The request method is written like this:
/**
* @description 查询用户详情
*/
export function getUserInfo() {
return http.get("/getUser");
}
In the following local configuration conversion, the address of our local request becomes http://123456.com/api
,
// 就是将 http://localhost/api 代理到 target/api
"/api": {
target: "http://123456.com",
...
}
What we actually want to access is http://123456.com/aaa/api/ccc
, so we need to rewrite the path, so we have the following configuration:
pathRewrite: {
"^/api": "/aaa/api/ccc", // 路径重写
},
This code is to rewrite http://123456.com/api
the in , that is , the local proxy is complete!/api
/aaa/api/ccc
http://123456.com/aaa/api/ccc
When going online, because no proxy is needed, path rewriting will fail, that is, the access address will change back http://123456.com/api
, so we need to modify the prefix in axios:
// baseURL: "/api", //本地
baseURL: "/aaa/api/ccc", // 测试服
that's all!