案例说明:
后端服务器接口(server.js):
const express = require('express')
const app = express()
// get请求
app.get('/user',(req,res) => {
res.json({
data:'XXX'
})
})
app.listen(3000, ()=> {
console.log('服务启动,端口 localhost:3000');
})
前端请求数据(index.js):
// 发送一个get请求
let xhr = new XMLHttpRequest();
xhr.open('get','http:localhost:3000/user', true);
xhr.onload = function(){
console.log(xhr.response)
}
xhr.send()
1 使用webpack提供的proxy方法配置
总体思路:从http//:localhost:80 请求 http//:localhost:3000/user 后台数据,会存在跨域问题,因此将前端发送时候的http//:localhost:3000/user 改为 api/user,通过proxy代理,将 api/ 开头的数据改为 http//:localhost:3000/ ,从而解决跨域问题
1.1 在webpack.config.js内,配置如下代码
module.exports = {
devSever: {
proxy: { // 代理 过滤以api开头的地址
'/api': {
target: 'http//:localhost:3000',
// 将api开头的地址重写为空,这样在后端地址上就不用加上api了
pathRewrite: {'/api' : ''}
}
}
}
}
1.2 index.js内,修改如下代码 请求地址'http://localhost:3000/user'修改为 'api/user'
// 发送一个get请求
let xhr = new XMLHttpRequest();
// 请求地址'http://localhost:300/user'修改为 'api/user'
xhr.open('get','api/user', true);
xhr.onload = function(){
console.log(xhr.response)
}
xhr.send()
2 在后台(serves.js)配置cors
cors就是在后台服务配置 allowCrossDomain
允许符合规范的请求源、请求头和请求方法通过
var allowCrossDomain = function(req, req, next) {
// 允许所有请求源 ajax http://localhost:80
res.header("Access-Control-Allow-Origin", "*");
// 允许所有请求头 x-token 等
res.header("Access-Control-Allow-Headers", "*");
// 允许所有请求方法 get post 等
res.header("Access-Control-Allow-Method", "*");
}
app.use(allowCrossDomain);
3 安装中间件:webpack-dev-middleware
webpack-dev-middleware 可以将前后端服务绑在一起,相当于部署为一个服务,就不存在跨域问题了
3.1 安装webpack-dev-middleware
cmd中运行 npm i -S webpack-dev-middleware
3.2 在后台服务(server.js)中配置如下
// 配置中间件
let webpack = require('webpack');
let middleware = require('webpack-dev-middleware')
let compiler = webpack(require('./webpack.config.js'))
app.use(middleware(compiler))