跨域问题
了解跨域问题
处于安全考虑,浏览器要求你的网站不能执行/访问其他网站的资源
跨域的影响
- 浏览器本地存储无法使用
- DOM对象,JS对象无法获取
- AJAX无法使用
跨域问题的解决
- 利用HTML标签的特性 script,a,iframe,img,link等
- 在前端使用代理解决
- 在服务器段解决
CORS - 跨域资源共享,通过添加响应头信息来解决
在Vue.js中解决
1. porxy代理
新建vue.config.js
// Node.js里面的模块
module.exports = {
// http://localhost:8080/api/test
// =>
// http://localhost:8000/test
devServer: {
proxy: {
'/api': {
// target: 'http://localhost:8000',
target: 'http://django.t.mukewang.com',
changeOrigin: true,
pathRewrite: {
// '^/api': '' //需要rewrite重写的URL
},
'/test': {
// target: 'http://localhost:8000',
target: 'http://localhost:9527',
changeOrigin: true,
pathRewrite: {
'^/test': '' //需要rewrite重写的URL
}
}
}
}
}
}
2. 通过axios来实现发送访问:
在main.js中导入已安装好的axios,并挂载到原型上
import { ajax } from '@/utils/ajax'
export default {
name: 'Home',
components: {
},
created () {
// ajax.get('http://django.t.mukewang.com/api/system/slider/list/?types=11')
ajax.get('http://localhost:8080/api/system/slider/list/?types=11').then(resp => {
console.log('返回的结果:', resp)
}).catch(err => {
console.log('请求出错:', err)
})
}
}