https://pro.ant.design/zh-cn/docs/proxy/
只为解决,在本地开发时XHR异步请求跨域问,并不适用线上环境
webpack devserver-proxy
https://webpack.js.org/configuration/dev-server/#devserver-proxy
https://www.jianshu.com/p/8fd5d7347c57
- content:用于定义哪些请求需要被目标主机代理
- option.target:目标主机(协议+主机名)
- 简写 var apiProxy = proxy(‘http://www.example.org/api‘);
options的几种配置
// 重写路径
pathRewrite: {'^/old/api' : '/new/api'}
// 移除路径
pathRewrite: {'^/remove/api' : ''}
// 添加基础路径
pathRewrite: {'^/' : '/basepath/'}
// 路径自定义
pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
In the function you get access to the request, response, and proxy options.
- Return null or undefined to continue processing the request with proxy.
- Return false to produce a 404 error for the request.
- Return a path to serve from, instead of continuing to proxy the request.
```jsx
devServer: {
proxy: {
‘/api’: {
}, }, },target: 'http://localhost:3000',
bypass: function (req, res, proxyOptions) {
if (req.headers.accept.indexOf('html') !== -1) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}
},
devServer: { historyApiFallback: true, hot: true, inline: true, progress: true, port: 3000, host: ‘10.0.0.9’, proxy: { ‘/api’: { target: ‘http://localhost‘, changeOrigin: true, secure: false, pathRewrite: {‘^/api’: ‘’} } }, }
var path = require(“path”); const context = [‘/api’, ‘/Uploads’] module.exports = { entry: ‘./src/entry.js’, output: { path: path.join(__dirname, ‘’), filename: ‘bundle.js’ }, devServer: { host: ‘’, port: ‘’, contentBase: ‘./‘, color: true, historyApiFallback: true, inline: true, proxy: [ { context: context, target: ‘http://xxx.xxxx.com/‘, secure: false, changeOrigin:true } ] },
![image.png](https://cdn.nlark.com/yuque/0/2021/png/112859/1631440990167-1b7f4b47-4c4a-4e84-9e33-fe0b465a3634.png#clientId=u9eb98840-9b3a-4&from=paste&height=401&id=uc25e234f&originHeight=535&originWidth=732&originalType=binary&ratio=1&size=234123&status=done&style=none&taskId=u633224e1-34fe-44d2-98aa-0d641b71357&width=549)
- 必须配置**changeOrigin= true**
- 黄框跟黄框所对应(/drink)
- 白框(/activity)在代理请求的时候会加在target所指的链接后面
<a name="Gdugt"></a>
## http-proxy-middleware
[https://github.com/chimurai/http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware)
<a name="wgYsn"></a>
### proxy工作原理
实质上是利用http-proxy-middleware 这个http代理中间件,实现请求转发给其他服务器。<br />例如:本地主机A为http://localhost:3000,该主机浏览器发送一个请求,接口为/api,<br />这个请求的数据(响应)在另外一台服务器Bhttp://10.231.133.22:80上,<br />这时,就可以通过A主机设置webpack proxy,直接将请求发送给B主机
<a name="U6op9"></a>
## 服务端解决跨域
nodejs
```jsx
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});