Body NULL NodeJS

0

I'm starting with nodejs, but whenever I try to send (email and password) to the API via POST, the typed values are returned as NULL.

router.post("/users", function(req, res){
        console.log(req.body)
        let query = "INSERT INTO ??(??,??) VALUES (?,?)";
        let table = ["user_login","user_email","user_password", req.body.email, md5(req.body.password)];
        query = mysql.format(query, table);
        console.log(query)
        connection.query(query, function(err, rows){
            if(err){
                res.json({"Error": true, "Message": "Erro ao executar a query do MYSQL"})
            }else{
                res.json({"Error" : false, "Message": "Usuario adicionado!"});
            }
        })
    });


REST.prototype.configureExpress = function(connection){
    let self = this;
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());

    let router = express.Router();
    app.use('/api', router);

    let rest_router = new rest(router, connection, md5);
    self.startServer();
}
    
asked by anonymous 24.05.2017 / 16:26

2 answers

0

I was able to solve it, the error was actually POSTMAN. so I'm setting the way to pass parameters, it was sending GET, even though I was switching to POST

    
25.05.2017 / 15:33
1
  

In postman, change your Headers to Content-Type: application/json :

  

ChangeinBodytoraw:

  

And,bydoingPost,theanswercame:

HereisthecodeIusedfortesting-server.js:

varexpress=require("express");
var bodyParser  = require("body-parser");
var app  = express();
var rest = require("./rest.js");
var router = express.Router();
app.use('/api', router);

function REST(){
    var self = this;
    self.configureExpress();
};

REST.prototype.configureExpress = function(connection){
    let self = this;
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());

    let router = express.Router();
    app.use('/api', router);

    let rest_router = new rest(router, connection);
    self.startServer();
}

REST.prototype.startServer = function() {
      app.listen(3000,function(){
          console.log("servidor trakinas");
      });
}

new REST();

E rest.js:

function REST_ROUTER(router,connection) {
    var self = this;
    self.handle_routes(router,connection);
}

REST_ROUTER.prototype.handle_routes = function(router,connection) {
    router.get("/bolacha", function(req,res) {
        res.json({"sabor" : "uva"});
    })

    router.post("/bolacha", function(req, res){
        res.send(200, req.body);
    });
}

module.exports = REST_ROUTER;

The source for this response is here .

    
25.05.2017 / 01:48