vue2项目解决跨域问题--了解前因后果
·
原因:前后端项目分离时前端的运行端口为:

以黑马项目的后端接口地址为例:

由于浏览器的同源策略:协议 域名 端口 3个都相同才是是同源
一个是http,另一个是https
一个是localhost,另一个又是hmajax.itheima.net
前端这个接口,请求实际已经返回了资源,只是CORS阻止了浏览器 读取 返回的资源。
那该如何解决这个问题?-----------使用vue.config.js代理
1.我们写接口的时候,一般是这样封装
import request from '@/utils/request'
/**
*
* 获取组织架构数据
*
*/
export function getDepartment() {
return request({
url: '/company/department'
})
}
请求的url是/company/department

在封装requset.js请求中会添加一个基础地址:/api,同时vue2框架还会自动添加协议 域名就是http://localhost:9529/
最后,前端的请求地址为http://localhost:9529/api/company/department
但实际的后端接口地址为:https://hmajax.itheima.net/api/company/department
那这一步怎么解决?----使用代理
找到vue.config.js文件中的devServer
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
proxy: {
'/api': {
target: 'https://heimahr.itheima.net'
}
}
// before: require('./mock/mock-server.js')
},
改段代码作用是当前端请求地址出现/api时,把/api之前的都替换成http://heimahr.itheima.net
之前:http://localhost:9529/api/company/department
之后:http://heimahr.itheima.net/api/company/department
更多推荐



所有评论(0)