由于我没有找到有关如何代理 devServer.proxy 的任何信息,因此我找到了一种解决方法:
我们需要使用另一个本地代理通过公司代理发送请求。这可以通过运行 httpServer (localhost:9009) 并获取我想发送到https://myProject.atlassian.net/rest/api/2 的请求的 nodejs 脚本来完成。然后,此 httpServer 会将我的请求发送到公司代理。 Webpack.devServer.proxy 配置现在看起来像这样:
'/api/*': {
target: 'http://localhost:9009',
headers: {
Authorization: 'Basic <someBase64EncodedString>',
Accept: "application/json"
},
secure: false,
changeOrigin: true,
pathRewrite: {
'^/api': ''
},
logLevel: 'debug'
}
httpServer "postproxy.js" 脚本可能如下所示:
var http = require('http');
var request = require('./node_modules/request');
var fs = require('fs');
var proxy = "<corporate proxy url>";
var api = "https://<myProject>.atlassian.net/rest/api/2/";
var hopper = "https://<myProject>.atlassian.net/rest/greenhopper/1.0";
http.createServer(function (reqorg, resorg) {
if (reqorg.method == 'POST'){
var bodyorg = '';
reqorg.on('data', function (data) {
bodyorg += data;
});
reqorg.on('end', function () {
var head = {
"content-type" : "application/json",
"Authorization": reqorg.headers.authorization
};
if(reqorg.url.includes("attachment")){
// Adjusting Head for Attachment Transfer
head["X-Atlassian-Token"] = "no-check";
head["content-type"] = "multipart/form-data";
var content = JSON.parse(bodyorg);
var buffer = Buffer.from(content.file,'base64');
var options = {
headers: head,
uri: api+reqorg.url,
formData: {
file: {
value: buffer,
options: {
filename: content.filename
}
}
},
method: 'POST'
}
request(options, function(err, response, body){
resorg.writeHead(200, {'Content-Type': 'application/json'});
resorg.end(body);
});
} else {
request.post({
headers: head,
url: api+reqorg.url,
proxy: proxy,
body: bodyorg
}, function(error, response, body){
resorg.writeHead(200, {'Content-Type': 'application/json'});
resorg.end(body);
});
}
});
} else if (reqorg.method == 'GET') {
request.get({
headers: {
'content-type' : 'application/json',
'Authorization': reqorg.headers.authorization
},
url: api + reqorg.url
}, function (error, response, body) {
resorg.writeHead(200, {'Content-Type': 'application/json'});
resorg.end(body);
})
} else if (reqorg.method == 'DELETE') {
request.delete({
headers: {
'content-type' : 'application/json',
'Authorization': reqorg.headers.authorization
},
url: api + reqorg.url
}, function (error, response, body) {
resorg.writeHead(200, {'Content-Type': 'application/json'});
resorg.end(body);
});
} else if (reqorg.method == 'PUT') {
var bodyorg = '';
reqorg.on('data', function (data) {
bodyorg += data;
});
reqorg.on('end', function () {
request.put({
headers: {
'content-type' : 'application/json',
'Authorization': reqorg.headers.authorization
},
url: hopper+reqorg.url,
proxy: proxy,
body: bodyorg
}, function(error, response, body){
resorg.writeHead(200, {'Content-Type': 'application/json'});
resorg.end(body);
});
});
}
}).listen(9009);
不要忘记在 package.json 中启动它:
"scripts": {
"start": "webpack-dev-server --mode development | npm run proxy",
"proxy": "node postproxy.js"
},