解决浏览器同源问题
代理服务器
原理
浏览器限制的是前端JavaScript直接发起的跨域请求
服务器之间没有同源限制
代理服务器作为中间层,前端请求同源的服务端接口,服务端再转发到目标服务器
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors');
const app = express();
// app.use(cors());
// 配置代理中间件
const proxy = createProxyMiddleware({
target: 'https://xxx.com/mbff',
changeOrigin: true,
secure: false,
pathRewrite: {
'^/mbff': '',
},
onError(err, req, res) {
console.log('onError', err);
},
});
// 使用代理中间件
app.use('/mbff', proxy, (req, res) => {
console.log('代理成功', req.url);
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
前端代码示例(假设你的Express服务运行在http://localhost:3000)
fetch('http://localhost:3000/mbff/api/products')
.then(response => response.json())
.then(data => console.log(data));
代理服务器会向目标服务器发送:
GET https://xxx.com/mbff/api/products开启非安全模式的浏览器
open -n /Applications/Google\ Chrome.app/ --args --disable-web-security --user-data-dir=/Users/edy/Desktop/ppp
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果