我有一个REST GET端点,该端点又向同一服务器中托管的端点发出HTTP POST异步请求。
我正在使用JavaScript中的XMLHttpRequest库发出POST请求。
这是我的代码段:
这是我的GET端点
@Get('/makePOSTreq')
public async MakePOSTReq(@Req() req: any, @Res() res: any, @Body() body: any) {
const str = 'HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello';
const buf = Buffer.from(str, 'utf8');
const formDataBoundary = '123sampleBoundary';
const formContentType = 'multipart/form-data; boundary=' + formDataBoundary;
let formDataStream = '';
let response = '';
const dstContentType = 'application/json';
const dstName = 'content';
const dstHeader = '--' + formDataBoundary + '\r\nContent-Disposition: form-data; name=' + dstName + '\r\nContent-Type: ' + dstContentType + '\r\n\r\n';
formDataStream += dstHeader;
const sourceType = { 'object ': 'objecrt'};
formDataStream += sourceType;
formDataStream += '\r\n';
const footer = '\r\n--' + formDataBoundary + '--\r\n';
const sampleContentType = 'application/octet-stream';
const sampleName = 'sampleData';
const sampleHeader = '--' + formDataBoundary + '\r\nContent-Disposition: form-data; name=' + sampleName + '\r\nContent-Type: ' + sampleContentType + '\r\n\r\n';
formDataStream += sampleHeader;
formDataStream += sampleData;
formDataStream += '\r\n';
formDataStream += footer;
const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/someurl', true);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', formContentType);
xhr.send(formDataStream);
xhr.onload = function() {
response = this.responseText;
};
return response;
}
如您所见,我正在对服务器本身内部托管的端点进行异步POST调用
这是我的服务器端代码:
@Post('/someurl')
public async ReturnData(@Req() req: any, @Res() res: any, @Body() body: any) {
console.log(req.body);
const response = '{ includeFilter: true }';
return res.write(response );
}
这里的问题是,一旦我发出POST请求,MakePOSTReq方法就会返回,并且在客户端,响应变得不确定。
我要等到异步POST请求返回数据,然后再将该数据返回给客户端。
我不希望MakePOSTReq立即返回。现在,响应对象包含一个空的''字符串,而不是实际的响应文本。