Home > other >  node.js / express, request body is null
node.js / express, request body is null

Time:04-06

learning express and for some reason my request body is NULL for both paramenters

my complete file for index.js:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000
const db = require('./queries')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
  }));

app.get('/',(request, response) => {
    response.json({info: 'express and postgresapi'})
})

app.post('/users', db.createUser)

app.listen(port, () => {
    console.log(`App running on port ${port}.`)
  })

and my queries file where I am making the POST

const Pool = require('pg').Pool
const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'chatDb',
  password: 'password1',
  port: 5432,
})

  const createUser = (request, response) => {
    const { name, email } = request.body

console.log(request.query);

pool.query('INSERT INTO users (name, email) VALUES ($1, $2)', [name, email], (error, results) => {
  if (error) {
      console.log(request.body)
    throw error
  }
  response.status(201).send(`User added with ID: ${results.insertId}`)
})

}

so this actually DOES post, but when I look at the rows in my db they are like

ID      name    email
20      NULL    NULL

my curl is curl --data "name=Elaine&[email protected]" http://localhost:3000/users

also, the outcome of console.log(request.query); is {}

CodePudding user response:

Hey you need to pass an object if your using postman

{
 "name":"your name here",
 "email":"email that you want"
}

Hope this helps

CodePudding user response:

  1. If you are sending request parameters as a params then use -
const createUser = (request, response) => {
    const { name, email } = request.query;

pool.query('INSERT INTO users (name, email) VALUES ($1, $2)', [name, email], (error, results) => {
  if (error) {
      console.log(request.body)
    throw error
  }
  response.status(201).send(`User added with ID: ${results.insertId}`)
})
  1. If you are sending request parameters within the body then use -
const createUser = (request, response) => {
    const { name, email } = request.body;

pool.query('INSERT INTO users (name, email) VALUES ($1, $2)', [name, email], (error, results) => {
  if (error) {
      console.log(request.body)
    throw error
  }
  response.status(201).send(`User added with ID: ${results.insertId}`)
})

** you can open your postman and you will get two options Params and Body Options. If you select Body then send the request body using either urlencode or json format because you added body-parser -

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
  }));
  • Related