Home > Software design >  I tried to request body json to node js using await fetch the body is empty
I tried to request body json to node js using await fetch the body is empty

Time:09-27

I'm new in node js so I tried to req fetch json post to node js using this code:

const req = await fetch(
    "http://localhost:3000/api/auth/signin", {
      method: "POST",
      header:{
        'Accept':'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username:myusername,
        password:mypassword
      })
    },
    
  )

But when I check in server side the body is empty, is there something that I missed?

This is my server side code:

exports.signin = (req, res) => {
    db.findByUsername(req.body.username,(err,data) =>{
        if(err){
            if (err.kind === "not_found") {
              res.status(404).send({
                message: `Not found customer with username or password.`
              });
            } else {
              res.status(500).send({
                message: "Error retrieving Customer with id "   req.body.username
              });
            }
        
          }
        console.log(data)
        if(data.password_user != req.body.password){
            return res.status(401).send({
                accessToken: null,
                message: "Invalid Password!"
              });

        }
     
    });
  
};

I tried to access with req.body.username but it's empty.

This is my route:

const { verifySignUp } = require("../middleware");
const controller = require("../controllers/auth.controller");

const bodyParser = require('express');


module.exports = function(app) {
    app.use(function(req, res, next) {
       

    res.header("Access-Control-Allow-Origin", "*");
    res.header(
        "Access-Control-Allow-Headers",
        "x-access-token, Origin, Content-Type, Accept"
    );
    next();
  });
  app.use(bodyParser.json());
  app.post("/api/auth/signin", controller.signin);
};

This is the error code:

TypeError: Cannot read property 'password_user' of null

CodePudding user response:

Firstly, the way you are adding the a middleware is wrong (I have never seen that to be honest). Here's what I was aiming to explain:

module.exports = function(app) {
    app.use(function(req, res, next) {
        // CORS handler
    });
    app.use(bodyParser.json());
    app.use('/api/auth/signin', controller.signin);
};

Also note the fact that your import is wrong:

const bodyParser = require('body-parser');

If I understand correctly, you want to patch your app which is an instance of an express application. In that case, you should add the body-parser middleware right before you add any handlers for POST and PUT request. Otherwise, the order of execution is wrong and the raw body from the request is never parsed and hence, req.body is undefined.

Edit

If you want to use body-parser for a single route, you can try the following:

app.route('/path/to', bodyParser.json(), function(req,res,next) { });

  • Related