在create-react-app
中,我可以在package.json
中使用proxy
自动配置代理,如这里所述的https://create-react-app.dev/docs/proxying-api-requests-in-development/
这允许我从不同的端口服务器我的应用程序。
如何在没有create-react-app
的情况下完成相同的配置?
如果有相同的代理来实现与create相同的配置,那就太好了。
发布于 2019-12-22 09:49:11
您可以创建一个与节点一起运行的文件作为代理。如下所示:
proxy.js
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({
secure: false,
changeOrigin: true,
target: 'https://someOriginURL.com',
// could be an IP address target: 'https://XX.XX.XXX.XXX/',
}).listen(3500, () => console.log('Proxy running on port 3500'));
// Intercepts the request
proxy.on('proxyReq', function(proxyReq, req, res, options) {
console.log(req);
// Set the headers of the intercepted request
proxyReq.setHeader('Origin', 'https://yourorigin.com');
// remove any headers you want
// proxyReq.removeHeader('authorization');
res.oldWriteHead = res.writeHead;
res.writeHead = function(statusCode, headers) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.oldWriteHead(statusCode, headers);
}
});
若要使用此操作,请打开终端并运行:
node proxy.js
请不要在生产中使用这个。
https://stackoverflow.com/questions/59446556
复制