如何解决NEXT.js API 路由不会接受 POST 请求
我在“pages/api/contact”设置了 Next.js API 路由。当我处理 GET 请求或导航到 localhost:3000/api/contact 时,我可以看到 api 正在工作。但是,每当我尝试处理对此 API 路由的 get 请求时,什么也没有发生。我曾尝试使用 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,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) {}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。