Home  >  Q&A  >  body text

Issues with efficiently sending arrays via POST method in Express

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:

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粉207969787P粉207969787369 days ago496

reply all(1)I'll reply

  • P粉543344381

    P粉5433443812023-09-17 00:59:05

    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 
    })

    reply
    0
  • Cancelreply