1、什么是跨域问题
当前页面的 协议、域名、端口, 这三者之一与请求 url的不同,即为跨域
如 协议不同
http://www.baidu.com
https://www.baidu.com
如 域名不同
https://www.baidu.com
https://taobao.com
如 端口不同
http://localhost:5500/index.html
http://localhost:6700/index.html
2、为什么会出现跨域问题
出于浏览器的同源策略限制,所谓同源就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)
以前开发很少出现跨域问题,因为基本都是后端 连同前端的一起开发的,
现在是前后端分离的开发模式,可能前端放在这个地址,后端接口放在那个地址,就会出现跨域问题
3、如何解决跨域问题
举个例子,现在前端使用 webpack的项目,进行网络请求
/* 网络请求的js代码 */
let xhr = new XMLHttpRequest();
xhr.open('get', 'http://www.xxxxxxxx.xxx/xxx', true);
xhr.onload = function() {
console.log(xhr.response)
}
xhr.send()
/* webpack.config.js 的配置文件 */
const path = require('path')
module.exports = {
// entry: 入口 output:出口
entry: './src/main.js',
output: {
// path: 绝对路劲 , 需要动态获取路劲
// path.resolve(__dirname, 'dist') --> 将获取当前项目的位置, 与dist进行拼接
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
}
}
果不其然,遇到了跨域问题
3.1、前端:Webpack proxy
使用webpack的 proxy的方式来解决跨域问题,就是使用一种代理的方式,将网络请求代理为你要请求的接口
/* 将请求方式改变为 本地的 http://localhost:5501/api/users */
let xhr = new XMLHttpRequest();
xhr.open('get', '/api/users', true); // 改变
xhr.onload = function() {
console.log(xhr.response)
}
xhr.send()
/* webpack.config.js 的配置文件 添加 proxy的代理模式 */
const path = require('path')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
devServer: {
proxy: { // 代理
'/api': { // 将 /api 开头的代理为 target 的路径
target: 'http://www.xxxxxxxx.xxxx',
pathRewrite: {'/api': ''} // 去除/api这个字符串
}
}
}
}
3.2、前端:Webpack plugin
3.3、中间件:nginx反向代理
3.4、后端:cors(推荐)
后端的我讲不清楚,可以看看这篇博客:https://blog.csdn.net/qq_38128179/article/details/84956552