I'm doing a project for school, I need to create a Rest API for a blog with Node.js. Users can post articles, and post comments related to these articles. For this project I'm using Sequelize and Express.
In my "comments" table, there is a "article" column which contains the title of the article where the comments has been posted. So I'm using a url like the following to get article's id, and then the title : /articles/:id/comments
The way I wanted the router's structure to be is the following :
POST localhost/articles/:id/commentsGET localhost/articles/:id/commentsGET localhost/articles/commentsThe problem is that when I make a GET localhost/articles/comments request, the router trigger this part of the code that leads to a Sequelize BAD_FIELD_ERROR :
file: routes/article.js
router.get("/:id", (req, res) => {
const id = parseInt(req.params.id);
Article.findByPk(id).then((article) => {
if (!article) res.sendStatus(404);
else res.json(article);
});
});
Instead of this part :
file: routes/article.js
router.get("/comments", (req, res) => {
const Query = req.query;
Comment.findAll({
where: Query
}).then((comments) => res.json(comments))
});
This is the server.js file :
const express = require("express");
const securityRouter = require("./routes/security");
const userRouter = require("./routes/user");
const articleRouter = require("./routes/article");
const verifyWebToken = require("./middleware/verifyWebToken");
const app = express();
const connection = require("./lib/db");
connection.sync();
app.use(express.json());
app.use("", securityRouter);
app.use("/users", userRouter);
app.use("/articles", verifyWebToken, articleRouter);
app.listen(3000, () => console.log("Server is listening."));