Home > Mobile >  req.body is always undefined in Express/bodyParser/NodeJS
req.body is always undefined in Express/bodyParser/NodeJS

Time:05-29

I'm having an issue where my req.body is always undefined when I do a POST. I'm using NodeJS, Express and BodyParser. Everything else I can find online says I need the include .json(), as below on the 1st line, but this didn't sort the issue. I've also tried with {extended: true} which also didn't help.

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(
    session({
        secret: 'my secret',
        resave: false,
        saveUninitialized: false,
        store: site
    })
);

If I run a line of code like req.body.text I'll just get undefined as the result. Does anyone know what my mistake might be?

CodePudding user response:

const app = express();
/* EXPRESS BODY PARSER */
app.use(express.json());
const myFunction(req,res) = async (req,res) => {

    const body = req.body;

}

CodePudding user response:

body parser is deprecated see https://stackoverflow.com/a/68127336/10772577.

Sending a post request to a route with 'Content-Type': 'application/json' should give you a body.

Example express route.

app.post('/api', function(request, response){
   console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

See https://expressjs.com/en/guide/routing.html

Example client request.

const response = await fetch('/api', {
    method: 'POST',
    body: JSON.stringify(object),
    headers: {
      'Content-Type': 'application/json'
    }
});

See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

  • Related