Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

reactjs - NEXT.js API route wont accept POST requests

I have a Next.js API route set up at "pages/api/contact". When I process a GET request or navigate to localhost:3000/api/contact I can see the api is working. However, whenever I try to process a get request to this API route nothing happens. I have tried using axios and fetch but nothing seems to work for post request. See below. Any help would be greatly appreciated.

called from a component when a button is clicked

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

};

in 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",
      });
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think it syntax error

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...