Undefined for the body of a request

Asked

Viewed 107 times

0

I’m trying to create a Postings in Node, where a post will have the following fields : Category, title and Description. The entity responsible for making this feature is called posts, which is configured as follows :

exports.up = function(knex) {
    return knex.schema.createTable('posts', function(table){
        //chave primária que se auto incrementa a cada post
        table.increments()

        table.string('category').notNullable()
        table.string('title').notNullable()
        table.string('description').notNullable()

    })
};

Done this I created a route to perform this feature, which is as follows :

routes.post('/postagens', (request, response) => {

    const data = request.body
    console.log(data)

    return response.json()
})

To test, I sent a request using the method POST with the content being sent in format JSON as follows :

{
    "category": "stackoverflow",
    "title": "erro à ser corrigido",
    "description": "retorno undefined"
}

This being said, I receive the following content on console.log(data) : Undefined.

How can I make to date receive the body of this my request ?

1 answer

1


Hello,

You can make the following code in your main file (usually the index.js):

const express = require('express');

const app = express();

app.use(express.json());

This allows the server to understand requests with the json

  • Oops, I put this on and I keep returning Undefined. Follow my index.js file currently : const express = require('express') const Routes = require('. /Routes') const app = express() app.use(Routes) app.use(express.json()) app.Listen(3333)

  • @Gabrielribeirocarneiro, then, puts the app.use(express.json()) before app.use(routes)

  • 1

    WORKED! Thank you very much

Browser other questions tagged

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