从Netlify函数中调用Nextjs API



我得到了一个类似这样的无服务器Netlify函数:

exports.handler = async function(event, context) {
return {
statusCode: 200,
body: JSON.stringify({message: "Hello World"})
};
}

当被此url<site-name>/.netlify/functions/helloworld调用时我确实收到消息{"message":"Hello World"}

我还得到了一个pages/api/mailingList.jsNextjs API端点:

const axios = require('axios');

export default async function handler(req, res) {
//console.log(req.query.mail);
if (req.method === "PUT") {
axios
.put(
"https://api.sendgrid.com/v3/marketing/contacts",
{
contacts: [{ email: `${req.query.mail}` }],
list_ids: [process.env.SENDGRID_MAILING_LIST_ID],
},
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
},
}
)
.then((result) => {
res.status(200).send({
message:
"Your email has been successfully added to the mailing list. Welcome   ",
});
})
.catch((err) => {
res.status(500).send({
message:
"Oups, there was a problem with your subscription, please try again or contact us",
});
console.error(err);
});
}
}

这个邮件列表API端点在从终端使用curl时起作用,方法是PUT:

curl -X PUT -d mail=helloworld@gmail.com  https://netlify.app/api/mailingList

当从mailingList.js中移除if (req.method === "PUT") {部分时,API端点也从URL(/api/mailingList?mail=helloworld@gmail.com)工作

但是,我无法从Netlify函数中调用API端点

(优选地,mailingListAPI应该能够基于不同的逻辑/api/mailingList?mail=helloworld@gmail.com&listid=xxx,使用来自Netlify函数helloworld.js的不同邮件列表ID来多次调用)

为了让API端点被调用,我尝试从函数中添加一个从helloworld.jsmailingList.js的axios调用,就像这个

const axios = require('axios');
exports.handler = async function(event, context) {

const mail = "helloworld@gmail.com";
// add to mailinglist
axios
.put("/api/mailingList?mail="+mail)
.then((result) => {
if (result.status === 200) {
toast.success(result.data.message);
}
})
.catch((err) => {
console.log(err);
});
}

这导致浏览器出现以下错误:error decoding lambda response: invalid status code returned from lambda: 0(我没有从Netlify日志中得到任何错误消息,无论是helloworld.js还是mailingList.js)

很明显,我从helloworld.js调用mailigList.js的方式有问题。如果有人能给我一些建议,告诉我我做错了什么,我将不胜感激。

如何从Netlify函数helloworld.js中调用API端点(mailigList.js)(最好多次使用不同的邮件列表ID:/api/mailingList?mail=helloworld@gmail.com&listid=xxx)

在本文中找到了解决方案:https://travishorn.com/netlify-lambda-functions-from-scratch-1186f61c659e

const axios = require('axios');
const mail = "helloworld@gmail.com";

exports.handler = (event, context, callback) => {
axios.put("https://<domain>.netlify.app/api/mailingList?mail="+mail)
.then((res) => {
callback(null, {
statusCode: 200,
body: res.data.title,
});
})
.catch((err) => {
callback(err);
});
};