I am new to express
and router. When I try to add a comment to the database, the console returned the error ("Post 400 Bad request" and "Uncaught in Promise"
). I’ve tried many solutions but it doesn’t work. I think it is to do with my routing.
Below is my profilesRouter.js in the backend folder:
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;
Here is my profilesController.js in the backend folder.
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;
On the other hand, for my frontend folder: Here is my 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> ); }
Upon clicking on individual profiles, it will bring me to 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;
Data is being stored in profile.json without the comments: [{"PROFILE_NUMBER": "A123", "NAME": "X", "AGE" : "21", "HOBBY" : "RUN"} , .....]
I am quite new and not sure how to debug it and push my comments into the database.
Advertisement
Answer
Try in this method
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: [] }) }) });