gpt4 book ai didi

javascript - Serverless NodeJS跳过https请求

转载 作者:行者123 更新时间:2023-12-02 23:31:27 24 4
gpt4 key购买 nike

我想发送 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);
};

我使用了异步等待,但没有返回任何内容(如果存在某种网络错误,我应该至少收到一个错误)

这是我的输出:在请求之前{ “状态代码”:200, "body": "{\"输入\":\"\"}"}

是不是少了点什么?

提前谢谢

最佳答案

您永远不会解决您的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();
})

关于javascript - Serverless NodeJS跳过https请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56480427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com