1.使用cors用后端的方式实现跨域,koa-cors
app.use(cors({
origin: 'http://localhost:8080', // 支持跨域访问的域名
credentials: true // 允许跨域带 cookie
}))
2.使用jsonp 实现前端跨域
let url = 'https://xxxxx'
jsonp(url,(err,res)=>{
})
3.接口代理,通过修改nginx服务器来实现(前端修改,后台不动)
在vue根目录创建文件 vue.config.js
意思是一个完整的URL 直接请求就会跨域,添加字段api 后通过代理发送请求
添加的字段如果在你的URL中那么就按照下面的写法,如果没有,那就将pathRewrite变成'/api':''
this.axios.post('/api/user/video_info', { vid: "168778" }).then(res => {
// ceshi fengag
console.log(res)
})
//vue.confgi.js内容
module.exports = {
devServer: {
host: 'localhost',
port: 8080,
proxy: {
'/api': {
target: 'http://localhost:3001', // 目标服务器地址
changeOrigin: true, // 默认false,是否需要改变原始主机头为目标URL
pathRewrite: { // 重新请求
'/api': '/api' // 是否需要api拼接
}
}
}
}
}
首先狭义的同源就是指,域名、协议、端口均为相同。
jsonp:
利用了 script 不受同源策略的限制
缺点:只能 get 方式,易受到 XSS攻击
测试:
// 加载本地json
this.axios.get('/mock/user/login.json').then(res => {
console.log(res)
})
this.axios.get('/user/login').then(res => {
console.log(res)
})
this.axios.post('/activity/servicetime').then(res => {
console.log(res)
})