我想发送一个https请求并使用无服务器框架处理结果,但是似乎不起作用。
Nodejs(无服务器)跳过我的请求,直接跳转到最后一个结果,而无需等待https响应
这里是我的功能
import { APIGatewayEvent, Callback, Context, Handler } from "aws-lambda";
var AWS = require("aws-sdk");
const querystring = require('querystring');
const https = require('https');
const TOKEN: String = "token";
export const hello: Handler = (
event: APIGatewayEvent,
context: Context,
cb: Callback
) => {
function https_request() {
var postData = querystring.stringify({
query: "query"
});
var options = {
hostname: 'example.com',
port: 443,
path: '/path',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': TOKEN
}
};
return new Promise(function(resolve, reject) {
console.log("before request")
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
if (res.statusCode !== 200) {
// REJECT IF THE RESPONSE WASN'T AS EXPECTED
return reject(new Error('Request failed'));
}
res.on('data', (d) => {
process.stdout.write(d);
resolve(d); // RESOLVE ON SUCCESS WITH EXPECTED DATA
});
});
req.on('error', (e) => {
console.error(e);
reject(e); // REJECT ON REQUEST ERROR
});
// req.write(postData);
req.end();
})
}
let x:any;
async function myAsyncF() {
x= await https_request();
console.log(x.body)
return x.body
}
myAsyncF()
const response = {
statusCode: 200,
body: JSON.stringify({
message: x,
input: event
})
};
cb(null, response);
};
我使用了异步等待,但是什么也没返回(如果出现网络错误之王,我应该至少收到一个错误)
这是我的输出: 在要求之前 { “ statusCode”:200, “ body”:“ {\” input \“:\” \“}” }
有什么遗漏吗?
提前谢谢
答案 0 :(得分:1)
您永远不会解决Promise
,我不知道您认为“成功”的请求是什么,但这是一个示例,可以使您走上正轨
return new Promise(function(resolve, reject) {
console.log("before request")
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
if (res.statusCode !== 200) {
// REJECT IF THE RESPONSE WASN'T AS EXPECTED
return reject(new Error('Request failed'));
}
res.on('data', (d) => {
process.stdout.write(d);
resolve(d); // RESOLVE ON SUCCESS WITH EXPECTED DATA
});
});
req.on('error', (e) => {
console.error(e);
reject(e); // REJECT ON REQUEST ERROR
});
req.write(postData);
req.end();
})