【问题标题】:Could not make POST request to add comments to my backend server无法发出 POST 请求以向我的后端服务器添加评论
【发布时间】:2022-10-05 18:20:02
【问题描述】:

我是express 和路由器的新手。当我尝试向数据库添加评论时,控制台返回错误 (\"Post 400 Bad request\" and \"Uncaught in Promise\")。我尝试了很多解决方案,但它不起作用。我认为这与我的路由有关。

下面是我在后端文件夹中的profilesRouter.js:

const express = require(\"express\");
const router = express.Router();

class profilesRouter {
  constructor(controller) {
    this.controller = controller;
  }
  routes() {
    router.get(\"/\", this.controller.getAll.bind(this.controller));
    router.get(
      \"/:profileId/comments\",
      this.controller.getComments.bind(this.controller)
    );
    router.post(
      \"/:profileId/comments\",
      this.controller.addComment.bind(this.controller)
    );
    return router;
  }
}

module.exports = profilesRouter;

这是后端文件夹中的profilesController.js。

const BaseController = require(\"./baseController\");

class profilesController extends BaseController {
  constructor(model) {
    super(model);
  }

  async getComments(req, res) {
    const { profileId } = req.params;
    try {
      const comments = await this.models.comment.findByPk(profileId);
      return res.json(comments);
    } catch (err) {
      return res.status(400).json({ error: true, msg: err });
    }
  }

  async addComment(req, res) {
    try {
      const comment = { ...req.body };
      const newComment = await this.models.comment.create(comment);
      return res.json(newComment);
    } catch (err) {
      return res.status(400).json({ error: true, msg: err });
    }
  }
}

module.exports = profilesController;

另一方面,对于我的前端文件夹: 这是我的 App.js:

import React from \"react\";
import { useState, useEffect } from \"react\";
import Single from \"./Single\";
import { Routes, Route } from \"react-router-dom\";

export default function App() {
  const [profiles, setprofiles] = useState([]);
  const getInitialData = async () => {
    let initialAPICall = await axios.get(
      `${process.env.REACT_APP_API_SERVER}/profiles`
    );
    setprofiles(initialAPICall.data);
  };

  useEffect(() => {
    getInitialData();
  }, []);

  return (
    <div className=\"App\">
      <Routes>
        <Route exact path=\"/\" element={<Home />}></Route>
        <Route
          exact
          path=\"/profiles\"
          element={<Card profiles={profiles} />}
        ></Route>
        <Route
          path=\"/profiles/:profileIndex\"
          element={<Single profiles={profiles} />}
        ></Route>
      </Routes>
    </div>
  );
}

点击个人资料后,它会将我带到 Single.js

import React, { useState, useEffect } from \"react\";
import { useParams } from \"react-router-dom\";
import axios from \"axios\";
import { BACKEND_URL } from \"../src/constant\";

const Single = ({ profiles }) => {
  const [comments, setComments] = useState();
  const [commentContent, setCommentContent] = useState(\"\");
  const { profileIndex } = useParams();
  const profile = profiles[profileIndex];

  console.log(profile);

  useEffect(() => {
    // If there is a profiles.id, retrieve the profile data
    if (profile.id) {
      axios
        .get(`${BACKEND_URL}/profiles/${profile.id}/comments`)
        .then((response) => {
          setComments(response.data);
        });
    }
    // Only run this effect on change to profiles.id
  }, [profile.id]);

  console.log(profile.id);

  if (!profile) {
    return \"No Profile\";
  }

  const handleChange = (event) => {
    setCommentContent(event.target.value);
  };

  const handleSubmit = (event) => {
    // Prevent default form redirect on submission
    event.preventDefault();

    // Send request to create new comment in backend
    axios
      .post(
        `${BACKEND_URL}/profiles/${profile.id}/comments`,
        {
          content: commentContent,
        }
      )
      .then((res) => {
        // Clear form state
        setCommentContent(\"\");

        // Refresh local comment list
        return axios.get(
          `${BACKEND_URL}/profiles/${profile.id}/comments`
        );
      })
      .then((response) => {
        setComments(response.data);
      });
  };

  // Store a new JSX element for each comment
  const commentElements = comments
    ? comments.map((comment) => (
        <ol key={comment.id}>
          {comment.createdAt} | {comment.content}
        </ol>
      ))
    : [];

  return (
    <div className=\"App\">
      <form onSubmit={handleSubmit}>
        <input
          // Use textarea to give user more space to type
          as=\"textarea\"
          name=\"content\"
          value={comments}
          onChange={handleChange}
        />
        <button variant=\"primary\" type=\"submit\">
          Submit
        </button>
      </form>
    </div>
  );
};

export default Single;

数据存储在 profile.json 中,没有 cmets:[{\"PROFILE_NUMBER\": \"A123\", \"NAME\": \"X\", \"AGE\" : \"21\", \"HOBBY\" : \"RUN\"} , .....]

我很新,不知道如何调试它并将我的 cmets 推送到数据库中。

  • 采取了哪些调试步骤?这是一个代码转储并要求我们对其进行调试,这不是 stackoverflow 的用途。你确定这是最小的重现后端错误所需的代码?见minimal reproducible example

标签: javascript sql node.js backend


【解决方案1】:

试试这个方法

router.post('/add', (req, res) => {

let { userid, comment } = req.body;

commentModel.create({

    userid: userid,
    comment: comment     

}).then((data) => {
    console.log("data-add", data);
    return res.json({
        success: true,
        message: "Comment added",
        data: data
    })
}).catch((error) => {
    console.log("error: ", error);
    return res.json({
        success: false,
        message: error.message,
        data: []
    })
 })
});

【讨论】:

    猜你喜欢
    • 2016-01-04
    • 2016-07-03
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2015-09-21
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多