跨域封装
CORS是一个W3C标准,全称是跨域资源共享(Cross-Origin Resource Sharing),也有译为 跨源资源共享。它允许浏览器向跨源服务器,发出XMLHttpRequest(XHR) 或Fetch API跨域 HTTP 请求,从而克服了同源使用的限制。
1使用代理服务器进行封装地址:在开发环境中,可以配置一个代理服务器来转发 API 请求,绕过浏览器的同源策略。在 vue.config.js 文件中进行配置,
module.exports = {
proxy: {
'/api': {
target: 'https://xxxxx.com',// 代理的目标IP地址
ws: true,// 是否代理websocket
changeOrigin: true, // 是否将主机头的源更改为目标URL,允许跨域
pathRewrite: {
'^/api': '/'//请求的时候使用这个api就可以
}
}
}
}
如若有问题可以使用’^/api’: ’ ',其他同理
module.exports = {
proxy: {
'/api': {
target: 'http://xxx.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
使用的时候以axios方法请求为例
import axios from 'axios'//记得引入
export function updatedInfo(data) {
return axios.post(
'/api/xxxxx', //XXXX为target中http://xxx.com后的请求后缀,例如:/userinfo
data,
)
}
在响应的页面请求接口使用function为updatedInfo的方法(方法名称可根据具体取)即可