一.项目中遇到的情景。
现在做的项目,未登录和登陆以后各自有首页,内容不一样。未登录的首页数据,需要请求另一个系统。(另一个系统也是同公司的)此时就出现了跨域,因为另一个系统接口域名和现在做的系统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,
},
};
附上讲解
这段代码是一个 JavaScript 模块,通过 CommonJS 的方式暴露了一个对象,这个对象包含了两个属性:
dev
和build
。这种模块导出方式常见于 Node.js 环境,通常用于配置文件或模块导出。下面是对每个属性的解释:
dev
: 开发环境的配置
assetsSubDirectory
: 静态资源存放的子目录,默认为 "static"。assetsPublicPath
: 静态资源在服务器上的公共路径,默认为 "/"。proxyTable
: 代理表,用于配置接口请求的代理,将匹配的请求代理到指定的目标地址。
- 在这里,所有以 "/train" 开头的请求将被代理到 "https://txxt.cmeconf.com/train"。
- 另外,一些特定的路径重写规则被定义,将请求路径映射到不同的目标路径。
host
: 开发服务器的主机名,默认为 "localhost"。port
: 开发服务器的端口号,默认为 8080。autoOpenBrowser
: 是否自动在浏览器中打开,默认为 false。errorOverlay
: 是否在浏览器中显示错误覆盖层,默认为 true。notifyOnErrors
: 是否在系统通知中显示编译错误,默认为 true。poll
: 是否使用轮询方式检查文件变化,默认为 false。devtool
: 生成 source map 的方式,在开发环境使用 "cheap-module-eval-source-map"。cacheBusting
: 是否启用缓存破坏,即在文件名中添加哈希值以防止缓存,默认为 true。cssSourceMap
: 是否生成 CSS source map,默认为 true。
build
: 生产环境的配置
index
: 生成的index.html
文件的路径,默认为 "../dist/index.html"。assetsRoot
: 打包后文件存放的根目录,默认为 "../dist"。assetsSubDirectory
: 打包后静态资源存放的子目录,默认为 "static"。assetsPublicPath
: 打包后静态资源在服务器上的公共路径,默认为 "./"。productionSourceMap
: 是否生成生产环境的 source map,默认为 false。devtool
: 在生产环境下使用的 source map 生成方式,通常是 "#source-map"。productionGzip
: 是否开启生产环境的 Gzip 压缩,默认为 false。productionGzipExtensions
: 指定哪些文件类型需要进行 Gzip 压缩,默认包括 "js" 和 "css"。bundleAnalyzerReport
: 是否生成打包分析报告,通过检查 npm 的配置项npm_config_report
决定。
题外话:
(本人前端小菜鸟,开发环境跨域是另一个前端小姐姐写的。本地正常,上线以后接口显示301,并且出现跨域问题,产品经理一直让我解决,我也不懂,一直改接口,一会把接口加个api,一会加个train,等等,后来咨询了其他前端才知道,上线以后,跨域问题要后端用nginx解决)