NEXT.js API 路由不接受 POST 请求
NEXT.js API route wont accept POST requests
我在“pages/api/contact”处设置了 Next.js API 路线。当我处理 GET 请求或导航到 localhost:3000/api/contact 时,我可以看到 api 正在工作。但是,每当我尝试处理对此 API 路由的获取请求时,什么都没有发生。我试过使用 axios 和 fetch 但似乎对 post 请求没有任何作用。见下文。任何帮助将不胜感激。
单击按钮时从组件调用
const handleClick = async (e) => {
e.preventDefault();
console.log("in handleSubmit");
try {
const res = await axios.post(
"http://localhost:3000/api/contact",
{
firstName,
lastName,
email,
},
{
headers: {
"Content-Type": "application/json",
},
},
console.log(res) //this comes back undefined
);
} catch (e) {}
};
在pages/api/contact
export default async function sendEmail(req, res) {
const { firstName, lastName, email } = req.body;
console.log(req.method);
if (req.method === "POST") {
return res.status(200).json({
message: "This is in post",
});
} else {
return res.status(200).json({
message: "This is not a post",
});
}
}
我认为是语法错误
try {
const res = await axios.post(
"http://localhost:3000/api/contact",
{
firstName,
lastName,
email,
},
{
headers: {
"Content-Type": "application/json",
},
},
);
console.log(res) //check now
} catch (e) {}
我在“pages/api/contact”处设置了 Next.js API 路线。当我处理 GET 请求或导航到 localhost:3000/api/contact 时,我可以看到 api 正在工作。但是,每当我尝试处理对此 API 路由的获取请求时,什么都没有发生。我试过使用 axios 和 fetch 但似乎对 post 请求没有任何作用。见下文。任何帮助将不胜感激。
单击按钮时从组件调用
const handleClick = async (e) => {
e.preventDefault();
console.log("in handleSubmit");
try {
const res = await axios.post(
"http://localhost:3000/api/contact",
{
firstName,
lastName,
email,
},
{
headers: {
"Content-Type": "application/json",
},
},
console.log(res) //this comes back undefined
);
} catch (e) {}
};
在pages/api/contact
export default async function sendEmail(req, res) {
const { firstName, lastName, email } = req.body;
console.log(req.method);
if (req.method === "POST") {
return res.status(200).json({
message: "This is in post",
});
} else {
return res.status(200).json({
message: "This is not a post",
});
}
}
我认为是语法错误
try {
const res = await axios.post(
"http://localhost:3000/api/contact",
{
firstName,
lastName,
email,
},
{
headers: {
"Content-Type": "application/json",
},
},
);
console.log(res) //check now
} catch (e) {}