Raghav
Raghav

Reputation: 480

POST Function in Express JS

I'm trying to create a basic login script for an app using Express JS, and have been working on a POST function to perform the same task for me. However, whenever I try to echo back the parameters I'm passing (testing the script via Postman), the values are always undefined.

Would appreciate some help! Thanks :)

Code:

 const express = require('express'),
 app = express();
 var bodyParser = require('body-parser');
 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({ extended: true }));



app.get('/',(request,response)=>{
  response.send('This is a test message');
});

app.post('/login', (request,response)=>{

    let uname = request.body.username;
    let pword = request.body.password;

    response.send('Username: ' + uname + ' and Password: ' + pword);
});

//Binding the server to a port(3001)
app.listen(3001, () => console.log('express server started at port 3001'));

JSON being passed:

{
  "username":"testuname",
  "password":"passw0rd"
}

Upvotes: 3

Views: 124

Answers (2)

sabbir
sabbir

Reputation: 2025

I think you should try as like as give below:

enter image description here

It works on my machine. As you might have seen that, I have select raw and JSON(application/json) which you might have been missing.

Upvotes: 1

Chris
Chris

Reputation: 2806

What you have works fine.

You are probably not specifying the Content-Type of your request to be application/json when testing.

Upvotes: 2

Related Questions