Search code examples
node.jsexpressnpmbody-parser

body-parser doesn't function for express


so, i got that "body-parser is deprecated" error when using app.use(bodyParser.urlencoded({extended:true})) and i think i fixed that using app.use(express.json) app.use(express.urlencoded({ extended: true })) but now my site won't load. I don't know exactly how this works, but this is all my nodejs code

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


app.use(express.json)
app.use(express.urlencoded({ extended: true }))
app.use(express.static('static'));

app.get('/', (req, res) => {
    res.sendFile("static/showcase.html", { root: __dirname });
});

so what's the problem and how can i fix it?


Solution

  • You forgot to call/initialize the express.json middleware. Also you can remove the body-parser require statement and remove it from your dependencies afterwards through npm uninstall body-parser:

    const express = require('express')
    const app = express()
    const path = require('path')
    const session = require('express-session')
    
    
    app.use(express.json())
    app.use(express.urlencoded({ extended: true }))
    app.use(express.static('static'));
    
    app.get('/', (req, res) => {
        res.sendFile("static/showcase.html", { root: __dirname });
    });