vue-cli 本地环境 API 代理设置和解决跨域

时间:2023-03-08 23:47:17
vue-cli 本地环境 API 代理设置和解决跨域
前言
我们在使用 vue-cli 启动项目的时候npm run dev便可以启动我们的项目了,通常我们的请求地址是以 localhost: 来请求接口数据的,localhost 是没有办法设置 cookie 的。 我们可以在 vue-cli 配置文件里面设置一个代理,跨域的方法有很多,通常需要后台来进行配置。我们可以直接通过 node.js 代理服务器来实现跨域请求。 vue proxyTable 接口跨域请求调试
在 vue-cli 项目中的config文件夹下的index.js配置文件中,dev长这样子: dev: {
env: require('./dev.env'),
port: ,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
cssSourceMap: false
}
服务器提供的接口如果长这样https://www.exaple.com/server_new/login,我们把域名提取出来如https://www.exaple.com; 在 config 中新建一个文件命名为proxyConfig.js: module.exports = {
proxy: {
'/apis': { //将www.exaple.com印射为/apis
target: 'https://www.exaple.com', // 接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewrite的,
}
}
}
}
config文件夹下的index.js引入proxyConfig.js: var proxyConfig = require('./proxyConfig')
config文件夹下的index.js中的dev改成: dev: {
env: require('./dev.env'),
port: ,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: proxyConfig.proxy,
cssSourceMap: false
}
重启项目npm run dev: 你会发现出现了这个 img 这个时候我们已经设置好了本地 API 代理了 修改本地hosts文件
文件路径一般是C:\Window\System32\drivers\etc,打开hosts文件,在这一段下面把localhost设置进去 # localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# :: localhost
127.0.0.1 activate.adobe.com
127.0.0.1 practivate.adobe.com
127.0.0.1 lmlicenses.wip4.adobe.com
127.0.0.1 lm.licenses.adobe.com
127.0.0.1 na1r.services.adobe.com
127.0.0.1 hlrcv.stage.adobe.com localhost www.exaple.com
搞定
此时我们已经完全解决了跨域问题,以及本地测试后台无法向我们本地环境设置cookie的情况了。 本文作者: IIsKei
本文链接: http://www.iskei.cn/posts/48205.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!