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

前言

我们在使用vue-cli启动项目的时候npm run dev便可以启动我们的项目了,通常我们的请求地址是以localhost:8080来请求接口数据的,localhost是没有办法设置cookie的。

我们可以在vue-cli配置文件里面设置一个代理,跨域的方法有很多,通常需要后台来进行配置。我们可以直接通过node.js代理服务器来实现跨域请求。

vue proxyTable接口跨域请求调试

在vue-cli项目中的config文件夹下的index.js配置文件中,dev长这样子:

?
1
2
3
4
5
6
7
8
9
dev: {
   env: require( './dev.env' ),
   port: 8080,
   autoOpenBrowser: true ,
   assetsSubDirectory: 'static' ,
   assetsPublicPath: '/' ,
   proxyTable: {}, 
   cssSourceMap: false
  }

服务器提供的接口如果长这样https://www.exaple.com/server_new/login,我们把域名提取出来如https://www.exaple.com;

在config中新建一个文件命名为proxyConfig.js :

?
1
2
3
4
5
6
7
8
9
10
11
module.exports = {
  proxy: {
     '/apis' : {  //将www.exaple.com印射为/apis
       target: 'https://www.exaple.com' , // 接口域名
       changeOrigin: true , //是否跨域
       pathRewrite: {
         '^/apis' : ''  //需要rewrite的,
       }      
     }
  }
}

config文件夹下的index.js引入proxyConfig.js:

?
1
var proxyConfig = require( './proxyConfig' )

config文件夹下的index.js中的dev改成:

?
1
2
3
4
5
6
7
8
9
dev: {
   env: require( './dev.env' ),
   port: 8080,
   autoOpenBrowser: true ,
   assetsSubDirectory: 'static' ,
   assetsPublicPath: '/' ,
   proxyTable: proxyConfig.proxy,
   cssSourceMap: false
  }

重启项目npm run dev:

你会发现出现了这个

这个时候我们已经设置好了本地API代理了

修改本地hosts文件

文件路径一般是C:\Window\System32\drivers\etc,打开hosts文件,在这一段下面把localhost设置进去

?
1
2
3
4
5
6
7
8
9
10
11
# localhost name resolution is handled within DNS itself.
# 127.0.0.1    localhost
# ::1       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   

搞定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丶乘风破浪丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值