NEXT.js API 路由不会接受 POST 请求

时间:2020-12-23 20:43:56

标签: reactjs http-post next.js

我在“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, 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",
      });
    }
}

1 个答案:

答案 0 :(得分:0)

我认为是语法错误

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) {}