解决vue项目的跨域请求问题

2022-09-12 07:59:11

刚来公司,被迫接收了一个前端任务(从未写过前端的我哭了),顶着头皮硬上,结果一运行就出现了跨域请求的问题,本着自己的事自己做的原则,我努力查找了半天,终于解决了,下面记录一下解决办法

1、出现的问题

XMLHttpRequest cannot load http://localhost:9090/. No 'Access-Control-Allow-Origin' 
header is present on the requested resource. 
Origin 'h(index):1ttp://localhost:8081' is therefore not allowedaccess.

从上面可以很明显地看出这是出现了跨域请求的问题了,下面就来讲一下怎么解决

2、解决办法

1)首先,需要在index.js中进行我们的属性配置(即添加我们的代理(proxy),用来解决跨域问题)
添加如下内容

module.exports={
	dev:{
		proxyTable:{'/api':{
				target:'http://****:9090',
				changeOrigin:true,
				pathRewrite:{'^/api':'/api'//这种接口配置出来的就是:http://****:9090/api/login//'^/api':'/' //这种接口配置出来的是:http://****:9090/login}}}}}

2)需要在dev.env.js中将我们的代理接口添加进去

module.exports=merge(pridEnv,{NODE_ENV:'"development"',API:'"/api"'}

上述配置后,我们就成功解决了跨域请求问题了

  • 作者:只要酸菜不要鱼
  • 原文链接:https://blog.csdn.net/qq_45559536/article/details/125439821
    更新时间:2022-09-12 07:59:11