当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。下面针对的是本地的跨域 => 比如一个前端端口是localhost:8080
后端开的端口localhost:8181前端直接调用就有可能会出现以下错误
后端阔以解决,前端也阔以解决
以vue为例在src同级文件下新建一个vue.config.js
然后配置以下内容
module.exports = {
devServer: {
proxy: { //配置跨域
'/api': {
target: 'http://localhost:8181', //这里后台的地址模拟的;应该填写你们真实的后台接口
changOrigin: true, //允许跨域
pathRewrite: {
/* 重写路径,当我们在浏览器中看到请求的地址为:http://localhost:8080/api/core/getData/userInfo 时
实际上访问的地址是:http://121.121.67.254:8185/core/getData/userInfo,因为重写了 /api
*/
'^/api': ''
}
},
}
},
}
举例1:访问后端http://localhost:8181/fruit/list
如果按照上面的配置下面就在 /fruit/list前多加一个/api就行 /api就会被vue替换成http://localhost:8181/
就是这样访问
axios.get("/api/fruit/list");
举例2:不加前缀标识符
module.exports = {
devServer: {
proxy: { //配置跨域
'/': {
target: 'http://localhost:8181', //这里后台的地址模拟的;应该填写你们真实的后台接口
changOrigin: true, //允许跨域
pathRewrite: {
/*这里不重写路径 直接就是访问*/
'^/': ''
}
},
}
},
}
这个访问就是这样
axios.get("/fruit/list");