Issues with efficiently sending arrays via POST method in Express
P粉207969787
P粉207969787 2023-09-16 21:10:57
0
1
575

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.

P粉207969787
P粉207969787

reply all(1)
P粉543344381

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; If infoBooks is an object containing stories, just import the object

2.) 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!

import {infoBooks} from "../data/books.js"
import express from "express";
const router = express.Router();

routerStories.post('/createNewBook', (req, res) =\> {
    const newBook = req.body;
    if(!newBook){
       res.status(400).json({message: "invalid arguments"})
       return
    }
    infoBooks.stories.push(newBook);
    //we don't need to set status here because by default the response will be 200
    res.json({infoBooks.stories});
    return 
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template