问题描述
我正在使用 NextJs,我正在尝试创建一个订阅表单,将数据发送到 MailChimp。但是,我收到错误提示
res.status 不是函数
这个文件在我的 pages/api
目录中。可能出了什么问题?
import { subscribe } from "../../lib/api";
const request = require("request");
export default async function subscribeWithEmail(req,res) {
const { email,js } = req.body;
const mcData = {
members: [
{
email_address: email,status: "pending",},],};
const mcDataPost = JSON.stringify(mcData);
const options = {
url: "https://us6.api.mailchimp.com/3.0/lists/SECRET",method: "POST",headers: {
Authorization: "auth APIKEY",body: mcDataPost,};
if (email) {
request(options,(err,res,body) => {
console.log(res);
if (err) {
res.json({ error: err });
} else {
if (js) {
res.status(200).send({ message: "yay" });
} else {
res.redirect("/");
}
}
});
} else {
res.status(404).send({ message: "Failed" });
}
// res.status(200).json(data);
return res.status(200);
}
解决方法
您正在隐藏初始 res
变量。
// you have another res here,which has nothing to do with Next.js res,but it is overriding it
// So you need to rename it to something else,for example to "response"
request(options,(err,response,body) => {
console.log(response);
if (err) {
res.json({ error: err });
} else {
if (js) {
res.status(200).send({ message: "yay" });
} else {
res.redirect("/");
}
}
});