4 votes

"Cannot POST" in node.js and postman

It happens that I have this code, where I try to pass by parameter the user and password using as a tool postman, honestly I am new to this so I do not know if I'm doing well or the code is wrong because I get this error in postman

introducir la descripción de la imagen aquí

app.post('api/v1/Login/:user/:pass',function(request, res){

 var usuario = request.params.user;
  var contraseña = request.params.pass;

  var request = new sql.Request();
  try{

  request.query("SELECT * FROM dbo.[Client] WHERE username = '"+UsuarioReg+"'AND pass = '"+ContraReg+"'", function (err, recordset) {
    if(err){
    console.log(err);
    }else{
      if(recordset.rowsAffected > 0){
        res.send(JSON.stringify("Usuario identificado correctamente"))
        res.send(JSON.stringify(recordset))
        console.log("Usuario identificado correctamente")
      }else{
        console.log("Usuario ["+UsuarioReg+"] no existe")
      }
    }
  })
}catch(err){
  res.send(JSON.stringify("Error while querying database :- "+err))
  console.log("Error while querying database :- "+err)
}

});

I would like to know what's wrong and how to solve it! Sorry if the question is not very clear.

0 votes

Try to send you the parameters in the URL. Example: api/v1/Login/usuario/contrasena

0 votes

Change from POST to GET

3 votes

@ValVert it would not be advisable to send by GET a username and password, it is totally exposed. My friend java005, when you use api/v1/Login/:user/:pass you are indicating that you are going to pass the parameters through the URL and not through the body that's why it doesn't find the route. You must send those parameters in a json and receive them in the back-end reading that json.

7voto

Phi Points 8436

My first recommendation is to disregard the comments of Mauricio Arias and Valvert, you should never send sensitive information by URL, and even less with a method like this GET much less when it comes to users and passwords.


The problem you are currently experiencing is because you are sending the parameters through the url, which is not correct and that's why it sends the error, basically it means that it does not find in endpoint you request from Postman.

To achieve what you need, to send data by a method POST you can make use of the body-parser The use and implementation are quite simple:

var express = require('express');
var bodyParser = require('body-parser')

var jsonParser = bodyParser.json()

app.post('/login', jsonParser, function (req, res) {
    if (!req.body)
        return res.sendStatus(400)
    console.log(req.body);

    var user = req.body.user;
    res.send('Bienvenido ' + user)
})

To make the call to the endpoint from Postman would be as follows:

  • URL: http://localhost :{port}/login (you should replace {puerto} for the one you currently use on your localhost
    • Method: POST
    • Headers: Content-type: application/json
    • Body: { "user" : "myuser", "pass":"mypass" }

Output on the console would be:

{ user: 'myuser', pass: 'mypass' }

The answer in Postman would be:

Welcome myuser


Making the total adjustment, your code would look like this:

app.post('/login', jsonParser, function (req, res) {
    if (!req.body)
        return res.sendStatus(400)

    var user = req.body.user;
    var pass = req.body.pass;

    var request = new sql.Request();
    try {
        request.query("SELECT * FROM dbo.[Client] WHERE username = '" + user + "'AND pass = '" + pass + "'", function (err, recordset) {
            if (err) {
                console.log(err);
            } else {
                if (recordset.rowsAffected > 0) {
                    res.send(JSON.stringify("Usuario identificado correctamente"))
                    res.send(JSON.stringify(recordset))
                    console.log("Usuario identificado correctamente")
                } else {
                    console.log("Usuario [" + UsuarioReg + "] no existe")
                }
            }
        })
    } catch (err) {
        res.send(JSON.stringify("Error while querying database :- " + err))
        console.log("Error while querying database :- " + err)
    }
})

0 votes

It worked perfectly! Thank you very much, I really appreciate it!!!!

1 votes

I'm glad @java005 :D There is only one thing to correct: the queries should not be concatenated, as far as possible it is better to use parameterized queries or Stored Procedures as it is susceptible to SQL Injection. Do some research about this and if you have any doubt we will be glad to solve it ;)

0 votes

I will do some research... thank you very much!

-1voto

ValVert Points 381

You could use this example as a basis. For the case you run a SP

exports.moduloValidacion = function(req, res)
{
    var post = {}
    sql.connect(config, function (err) {
        if (err)
        {
            console.log("Log Error"+' '+err.originalError);
            res.status(500).send(err.originalError);
        }
        else
        {
            var request = new sql.Request();
            request.input('user', req.body.user);
            request.input('pass', req.body.pass);
            request.execute('SPValidaUsuario', (err, result) => {
                if(err){console.log("Log Error"+err.originalError.info.message);
                    res.status(500).send(err.originalError.info)}
                else
                {
                    if(result)
                    {
                        console.log("Log Ok");
                        res.status(200).send(result.recordsets[0])
                    }
                }
                sql.close()
            })
        }                   
    })
};

1 votes

I believe that your recommendation could only confuse the OP since the user is trying to make a POST call, then execute a query, not us SP as you indicate.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X