一.项目中遇到的情景。
现在做的项目,未登录和登陆以后各自有首页,内容不一样。未登录的首页数据,需要请求另一个系统。(另一个系统也是同公司的)此时就出现了跨域,因为另一个系统接口域名和现在做的系统ip不一样。
二.跨域解决方案
在开发过程中,需要前端来解决,一般用proxy
在上线以后,生产环境中就需要后端用nginx来解决
proxy可以解决跨域问题。但是只能在开发过程中使用,一旦项目上线,就必须要后端用nginx来解决了。
三.proxy的用法
1.在项目里一般写在vue.config.js文件里面(位置和src平级)
module.exports = {
dev: {
assetsSubDirectory: "static",
assetsPublicPath: "/",
proxyTable: {
"/train": {
target: "https://txxt.cmeconf.com/train",
changeOrigin: true,
pathRewrite: {
"^/train": "/",
// lamp-boot 项目 请使用以下的配置
["^/api/oauth/"]: "/",
["^/api/authority/"]: "/",
["^/api/msg/"]: "/",
["^/api/file/"]: "/",
["^/api/gateway/"]: "/gateway",
["^/api/gate/"]: "/",
["^/api/activiti/"]: "/",
},
},
},
host: "localhost", // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
//还原
devtool: "cheap-module-eval-source-map",
cacheBusting: true,
cssSourceMap: true,
},
build: {
// Template for index.html
index: path.resolve(__dirname, "../dist/index.html"),
assetsRoot: path.resolve(__dirname, "../dist"),
assetsSubDirectory: "static",
assetsPublicPath: "./",
//还原
productionSourceMap: false,
devtool: "#source-map",
productionGzip: false,
productionGzipExtensions: ["js", "css"],
bundleAnalyzerReport: process.env.npm_config_report,
},
};
附上讲解
题外话:
(本人前端小菜鸟,开发环境跨域是另一个前端小姐姐写的。本地正常,上线以后接口显示301,并且出现跨域问题,产品经理一直让我解决,我也不懂,一直改接口,一会把接口加个api,一会加个train,等等,后来咨询了其他前端才知道,上线以后,跨域问题要后端用nginx解决)