在vue中使用proxy进行跨域的原理是:将域名发送给本地的服务器(启动vue项目的服务,比如loclahost:8080),再由本地的服务器去请求真正的服务器。
需要再vue-config.js配置,具体代码如下:
const { defineConfig } = require("@vue/cli-service"); module.exports = defineConfig({ transpileDependencies: true, devServer: { proxy: { "/data": { target: "http://localhost:8002", pathRewrite: { "^/data": "" }, //如果有/data,那就不用配置了,否则需要重写 // ws:true, //用于支持websocket // changOrigin:true //用于控制请求头的host值,是否跨域 }, }, }, } })
注:因为修改了vue-config.js,需要重启一下项目