1

I write this code and req.body is undefined I want to get post value in my program can you help me, please?

const express = require('express')
const app = express()
const port = 3000
const crypto = require('crypto');
function sha1(s) {
    return crypto.createHash("sha1")
        .update(s)
        .digest("hex");
}
app.post("/flag", (req, res) => {
    console.log(req.body);
});


app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

2 Answers2

2

You body-parser npm package

$ npm i body-parser
var express = require('express')
var bodyParser = require('body-parser')
const app = express()
const port = 3000
const crypto = require('crypto');

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

function sha1(s) {
    return crypto.createHash("sha1")
        .update(s)
        .digest("hex");
}
app.post("/flag", (req, res) => {
    console.log(req.body);
});


app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Sai Kumar
  • 287
  • 1
  • 5
2

Instead of using body parser, Express already providing support for that,

import express from "express";  
const app = express(); 

app.use(express.json()); 
app.use(express.urlencoded());

This should be given before the Api route

droid kid
  • 7,569
  • 2
  • 32
  • 37