vue3解决跨域问题详细代码亲测有效
目录
- vue3解决跨域问题详细代码亲测有效
- 关于解决vue3的跨域问题
- 项目场景:
- 原因分析:
- 解决方案:
vue3解决跨域问题详细代码亲测有效
1.在vue.config.js中 放入以下代码:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://api.tubecoin.org', //这里填入你要请求的接口的前缀
ws: true, //代理websocked
changeOrigin: true, //虚拟的站点需要更换origin
secure: true, //是否https接口,我用的http但是我变成false他打包后会报错,所以先true
pathRewrite: {
'^/api': '' //重写路径
}
}
}
}
}
2. 需要写接口的页面引入:
import Axios from "axios"; Axios.defaults.baseURL = "/api";
3.页面中的方法:
Axios({
method: "post", //接口方法
url: "/register/register", //接口
params: { //需要传的参数
username: obj.name,
phone: obj.phone,
sms_code: obj.code,
},
}).then((res) => {
console.log(res, "55555");
ElMessage(resp.data.message); //这个是引入的element plus中的提示框
});
关于解决vue3的跨域问题
项目场景:
提示:这里简述项目相关背景:
当我们使用vue3搭建前后端分离项目时,往往会出现跨域问题。前端往往会提示:

原因分析:
例如,我这里,前端的项目的请求地址是http://localhost:8085/,访问后端的接口为http://localhost:8081/ResourcesCenter/BaseMapStyle/selectByPage,由于端口的不一致,所以出现了跨域问题。
解决方案:
第一步:找到vue.config.js文件,添加如下代码:
module.exports = {
devServer: {
open: true,
host: 'localhost',
port: 8085,
//这里的ip和端口是前端项目的;下面为需要跨域访问后端项目
proxy: {
'/ResourcesCenter': {
target: 'http://localhost:8081/ResourcesCenter/',//这里填入你要请求的接口的前缀
ws:true,//代理websocked
changeOrigin:true,//虚拟的站点需要更管origin
secure: true, //是否https接口
pathRewrite:{
'^/ResourcesCenter':''//重写路径
},
headers: {
referer: 'http://localhost:8081/ResourcesCenter/', //这里后端做了拒绝策略限制,请求头必须携带referer,否则无法访问后台
}
}
}
}
}
第二步,就是如何调用了
selectByPage(pageSize, pageNum, keyword) {
return axios.get('/ResourcesCenter/BaseMapStyle/selectByPage?almanacName='+keyword+'&pageSize='+pageSize+'&pageNum='+pageNum,
// {
// params:{
// almanacName:keyword,
// pageSize:pageSize,
// pageNum:pageNum
// }
// },
/*' {headers: {\'Content-Type\': \'application/json;charset=UTF-8\'}}'*/)
}

本人亲试,已成功解决!
到此这篇关于vue3解决跨域问题详细代码亲测有效的文章就介绍到这了,更多相关vue3解决跨域内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)
