Post goes as Null in the Node api

Asked

Viewed 30 times

-1

I am learning how to create a simple API with Node. The get works perfectly, but the post ends up going like null.

The code goes like this

const express = require('express');
const server = express();
server.use(express.json()); // faz com que o express entenda JSON
const geeks = [
    {
        'nome': 'ricardo'
    }
]; // As informações ficaram armazenadas dentro deste array []

server.get('/geeks', (req, res) => {
    return res.json(geeks);
}) // rota para listar todos os geeks

server.get('/geeks/:index', (req, res) => {
    return res.json(req.user);
})

server.post('/geeks', (req, res) => {
    // assim esperamos buscar o name informado dentro do body da requisição
    const { name } = req.body; 
    geeks.push(name);
    return res.json(geeks); // retorna a informação da variável geeks
})


server.listen(8080)
  • 1

    how you are sending the request?

  • I’m tested by Postman

  • 1

    spend the way you’re doing!?

  • I run the POST for http://localhost:8080/geeks. the header has selected the content-type application/x-www-form-urlencoded , and the body esta x-wwww-form-urlencoded.

  • 1

    has to be json!

  • got it. I changed the body to apliccation/json and managed to send the post. thanks!!

Show 1 more comment

1 answer

1

Hello, Ricardo

Despite not having enough information on your question, I decided to test your code locally.

It is working "perfectly" as expected (according to the code)...

It may be that in the post request you are sending the property name with another nomenclature, so it is being received as null (maybe you are sending nome).

One correction is that in geeks.push(name); you could do it this way: geeks.push({name});

  • I traded for geeks.push({name}); and sends the empty object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.