如何解决提取API的响应时间过长?
我正在使用netlify的lambda函数来开发无服务器应用程序。
从一个lambda函数中,我使用node-fetch
包将POST请求发送到服务器的API。
请求成功,但是第一个请求花费的时间太长(16450毫秒),对于其他后续请求,则花费的时间约为3000-4000毫秒。
尽管使用 postman ,但需要花费约3000毫秒的时间。即使是第一个请求。
这是我的lambda函数代码,
const fetch = require("node-fetch");
const dotenv = require("dotenv");
dotenv.config();
exports.handler = (event,context,callback) => {
if (event.httpMethod !== "POST") {
return callback(null,{
statusCode: 400,});
}
const responseFromFacebook = event.body;
const API_URL = process.env.API_CREATE_CONTRIBUTOR_URL;
// the "callback" is used to send response back to the client.
function sendToClient({ status,data }) {
return callback(null,{
statusCode: status,body: JSON.stringify(data),});
}
let statusFromNoteIT;
console.time("execution");
fetch(API_URL,{
method: "post",headers: {
Accept: "application/json","Content-Type": "application/json",},body: responseFromFacebook,})
.then((res) => {
console.log(res);
statusFromNoteIT = res.status;
if (
statusFromNoteIT === 202 ||
statusFromNoteIT === 201 ||
statusFromNoteIT === 200
) {
return res.json();
} else {
throw new Error(`The server responded with ${statusFromNoteIT}`);
}
})
.then((data) => {
console.log(data);
if (statusFromNoteIT === 202) {
console.timeEnd("execution");
return callback(null,{
statusCode: statusFromNoteIT,headers: {
"Set-Cookie": `token=${data.success}; httpOnly=true; max-age=1800; sameSite=strict`,});
} else {
console.log("sending error response on first try ?");
sendToClient({
status: statusFromNoteIT,data: data,});
}
})
.catch((error) =>
sendToClient({
status: statusFromNoteIT,data: error,})
);
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。