1、CORS跨越-服务端设置,前端直接调用
说明:后台允许前端某个站点进行访问
(1)CORS请求默认不‘发送Cookie和HTTP认证信息。如果要把Cookie发到服务器,一方面要服务器同意,指定Access-Control-Allow-Credentials
字段:
Access-Control-Allow-Credentials: true
(2)另一方面,开发者必须在AJAX请求中打开withCredentials
属性:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
2、JSONP跨域-前端适配,后端配合
说明:前后台同时改造
使用jsonp插件
下载方式:
npm i jsonp --save-dev
使用方式:
josnp(url,(err,res)=>{
console.log(res)
})
3、接口代理-通过修改nginx服务器配置来实现
说明:前端修改,后台不动
vue-cli 2.0 在confog文件下index.js中改动
vue-cli@4.0 项目基于根目录下新建vue.config.js文件
代码如下:
module.exports = {
desServer:{
host:'localhost',
port:8080,
proxy:{
'/api':{
target:'https://www.imooc.com',//目标地址
changeOrigin:true, //是否开启代理
pathRewrite:{
'^/api':'/api'
}
}
}
}
}
访问方式:https://www.imooc.com/crested/list
变更为:/api/crested/list