vue怎么解决“跨域”

mac2024-05-11  35

报错图和报错代码

Access to XMLHttpRequest at 'https://xin.yuemei.com/V603/channel/getScreenNew/' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. createError.js?c3b5:16 Uncaught (in promise) Error: Network Error at createError (createError.js?c3b5:16) at XMLHttpRequest.handleError (xhr.js?363a:81)

像这种情况就属于跨域报错。

首先让我们了解一下为什么会出现跨域报错? 一个网页向另一个不同域名/不同协议/不同端口的网页请求资源,这就是跨域。跨域报错就是请求终端不允许不同的域名、协议、端口访问,结果你用了,然后就返回报错。

解决方法:在脚手架中的config下的index.js中

在 dev 的 proxyTable 对象中添加这些属性

// Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { "/apx":{ target:"https://xin.yuemei.com/V603/channel/getScreenNew/",//接口域名 changeOrigin:true,//是否跨域 pathRewrite:{ "^/apx":""//重写为空 } } },

然后请求这里用axios请求

axios.post("/apx").then(res => { console.log(res); this.data = res.data.data; }); //如果有参数请求 axios.post("/apx?key=111").then(res => { console.log(res); this.data = res.data.data; });

这样就可以了,不行的话就去蓝翔吧,那里师资力量不错。

最新回复(0)