我的请求正在响应404错误,但已按照预期发布

问题描述

请尝试使用express和sendGrid创建联系人。一切似乎都可以正常工作,但由于某种原因,我在请求中收到404错误,但消息按预期发送。我不明白如何在请求中收到404错误,但消息发送得很好。我的代码

Front-End Code 
const [message,setMessage] = useState({
    first_name: "",last_name: "",email: "",website: "",subject: "",message: "",email_sent: null,disable: false,});
  function handleSubmit(e) {
    e.preventDefault();
    Axios.post("/api/email",message).then((res) => {
      console.log(res);
      if (res.data.success === true) {
        setMessage({
          disable: false,email_sent: true,});
      } else {
        setMessage({
          disable: false,email_sent: false,}).catch((error) => console.log(error));
      }
    });

Back-End Code.

const express = require("express");
const cors = require("cors");
const sendGrid = require("@sendgrid/mail");
const { restart } = require("nodemon");

const app = express();
app.use(cors());
app.use(express.json());

app.get("/api",(req,res,next) => {
  res.send("API STATUS: RUNNING");
  next();
});

app.post("/api/email",next) => {
  sendGrid.setApiKey(
    "myAPIkey goes here"
  );
  const msg = {
    to: "email I am sending to goes here",from: "mysendGrid Verified sender email goes here",email: req.body.email,subject: req.body.subject,text: req.body.message,};
  sendGrid
    .send(msg)
    .then((result) => {
      res.status(200).json({
        success: true,});
    })
    .catch((err) => {
      console.log("error:",err.toString());
      res.status(401).json({
        success: false,});
    });
  next();
});

app.listen(5000);

Thank you.

解决方法

尝试使用.send()方法。像这样:

.then(result => {
  res.status(200).send({success : true});
})

希望这可以解决问题:-)