Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
I tried to request body json to node js using await fetch the body is empty

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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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) { });

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!