Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda