Anıl Atasoy
Anıl Atasoy

Reputation: 15

Why my nodejs POST request returns null values (I use postman)?

When I use post request it only posts null I use postman

app.post("/books",async (req,res)=>{
  try{
      
  const {book_name,book_author,book_desc} = req.body;
  const newBook =  await pool.query("INSERT INTO library(book_name,book_author,book_desc) VALUES($1,$2,$3) RETURNING *",
  [book_name,book_author,book_desc]);
  res.json(newBook.rows[0]);
   }
  catch(err){
      console.error(err.message);
  } 
  
})

This is the code and output of postman:

{ "book_name": "abc", "book_author": "def", "book_desc": "gjl"

}

Output:

{ "book_id": 1, "book_name": null, "book_author": null, "book_desc": null }

Upvotes: 0

Views: 1471

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

You are missing json parser so your req.body is not getting book_name, book_author and book_desc.

use json() middleware before the post code and you are good to go.

For TS:

import express, { json } from "express";
app.use(json()) // use json parser to convert the body to json for upcoming method to consume

app.post("/books",async (req, res)=>{
...
})

For JS:

const express = require('express');
app.use(express.json())

app.post("/books",async (req, res)=>{
...
})

Upvotes: 1

Related Questions