I'm new here and learning Express, and while I think I'm on the right track, I'm currently having some issues with the POST
method. The situation I am encountering now is as follows:
When I send a POST
request to an http file, I receive an empty object {}
. Additionally, I tested via Thunder client, but I received a 400 error or other http error.
Content-Type: application/json
does not work under the path in the http file.
GET
method works fine.
This is the code I've been using:
const express = require('express'); const { stories } = require('../data/books.js').infoBooks; const routerStories = express.Router(); routerStories.use(express.json()); routerStories.post('/', (req, res) => { const newBook = req.body; stories.push(newBook); res.send(JSON.stringify(stories)); });
I've been trying to solve it for a few days. Even though I've done a lot of research, I just can't figure it out. Please give your perspective and experience to be able to solve this problem.
I found some problems in your code. I'm assuming you pasted the original code, so here's what you need to change.
1.) I don't think this line is valid javascript code, or if it is, it's a little weird.
const { stories } = require('../data/books.js').infoBooks;
IfinfoBooks
is an object containing stories, just import the object2.) You don’t need to set the route to json, because the route has this method by default and will accept json as a valid response
3.) Maybe you are not using a different route name and another route is using the same string literal.
You didn't provide enough information, so there may be other issues with your use of routing itself, but based on what you posted, these are all the issues I found. hope this helps!