A
A
Alexander2020-08-24 15:07:31
Node.js
Alexander, 2020-08-24 15:07:31

body-parser not working?

I'm building an app to deal with REST APIs using the JS stack, NodeJS. Front on Vue if that matters.
On the server side, I use express.js.
Starting from version 4, they cut out the body-parser from express itself and it must be connected separately.

Connected body-parser, but it doesn't work. req.body === undefined

app.js (node)

const express = require( 'express' );
const path = require( 'path' );
const app = express();
const bodyParser = require('body-parser');

const CONTACTS = [
    { id:1, name: 'Test', value: 'test', marked: false }
];

app.get( '/api/contacts', ( req, res ) => {
    res.status( 200 ).json( CONTACTS );
});

app.post( '/api/contacts', (req, res) => {
    console.log( req.body ); // undefined
    res.json( CONTACTS ); // all ok
})

app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: false }));

app.use( express.json() );
app.use( express.static( path.resolve( __dirname, 'client' )));
app.get( "*", (req, res) => {
    res.sendFile( path.resolve( 'client', 'index.html' ) )
});
app.listen( 3000, () => console.log( '3000...' ) );


Googled a lot, nothing helped. It seems that the error is at the "Declared, but not called" level.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WapSter, 2020-08-24
@Aleksandr-JS-Developer

You accept requests before midway body parser declares, move the routes to the server call.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question