'Why Does My req.body Return Empty on Express

I can't understand why I'm getting an empty req.body {} in client side I get undefined or when I try to use payload = req.body.payload and console.log(payload) I get undefined on the server side and on the client side I get (chrome developer tool console) ERROR TypeError: Cannot read properties of null (reading 'payload').

What I don't understand is the server receives the request payload(status 201) the response payload is empty, also correct me if I'm wrong the response is a JavaScript object and in the service the original payload is contained so shouldn't I get that in the response.

I have looked at many topics that have the same issue. I'm already doing things that fixed some of the issues.

I have a Content-Type application/json, I apply the app.use(json()) before I use my routes, which seemed to have been the problem with some. Yet I still get empty re.body. I have tried so many things with no luck. Am I missing something? Code snippet.

I would appreciate a point in the right direction

Thanks In Advance PH.

service.ts

export interface Products{
  _id: string,
  name: string
}


@Injectable({
  providedIn: 'root'
})
export class SearchService {

 
  constructor(private http:HttpClient) { }
  
 
 
  searchProducts(query:string){
    console.log("Does it get  my  searchProducts");
    return this.http.post<{payload: Array<Products>}>(productsUrl, {payload: query}, {
     
     headers: new HttpHeaders({'Content-Type': 'application.json'})       
    }).pipe(
       map(data => data.payload)
     
    );
        
  }
  
}

header.ts

sendData(event:any){
  
  //console.log(event.target.value);
  let query:string = event.target.value;
  //Will match if query is nothing or only spaces
  let matchSpaces:any=query.match(/\s*/);
  console.log("What about match");
     if(matchSpaces[0] === query){
    console.log("What about query");
      //.products=[];
   console.log("what is in collection", this.products);
      this.hasQuery = false;
    return;

  }
  console.log("about to call service")
  this.searchService.searchProducts(query.trim()).subscribe((results) =>{
    console.log("does it get pass subscribe")
   // this.products = results;
    this.hasQuery = true;
    console.log(results);
   
  })
 }

route file getProducts.js

var express = require('express');
const cors    = require('cors');
var bodyParser = require('body-parser')
const Products      = require('../../../liveSearch');
const { query } = require('express');
var router = express.Router();
const app = express();

 
   router.get('/', function(req, res){
   res.send('GET route on api here.');
});


/*router.post('/getproducts', function(req,res){
  
    res.send("Trying to post")
   
});*/

/*app.use(cors());
var corsOptions = {
  origin: 'http://localhost:4200',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}*/




router.post('/getProducts', async(req, res) =>{
   
     let payload=req.body;
     //let payload= req.body.payload;

     let search = await Products.find({name: {$regex: new RegExp('^'+payload+'.*',
   'i')}}).exec();
     //Limit search to 10
       search = search.slice(0, 10);
       
     
      console.log("Payload", payload) 
     //.log("Inside search",search);
      res.status(201).json(payload)  //added to see why I couldn't get 
 response
     // res.send({payload:search});
    
     
})


server.js

const express = require('express');
const cors    = require('cors');
const router = express.Router();
var bodyParser = require('body-parser');
const Products = require('./liveSearch');
const getProducts = require('.../../controllers/api/getProducts/getProducts')
//const products = require('.../../routes/products.js')



const mongoose = require('mongoose');
//mongoose.Promise = Promise;


mongoose.connect('mongodb://localhost/productLiveSearch', {useNewUrlParser:
true, useUnifiedTopology: true, }); 
const db = mongoose.connection;
db.on('error', error => console.log(error));
db.once('open', () =>{  console.log('Connected to Mongoose')});

 const app = express();

app.use(function(req,res,next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('content-type','application/json');
  res.header('Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Methods','POST, GET, DELETE, PUT, OPTIONS');
  res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
  next();
  });

 
app.use(cors());
var corsOptions = {
  origin: 'http://localhost:4200',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}


  app.use(express.json());
  app.use(express.urlencoded({extended:true}));
 // app.use(express.json({ limit: "1000mb" }));
 // app.use(express.urlencoded({ limit: "1000mb", extended: true }));
 
  app.use('/', getProducts);
  app.use('/getProducts', getProducts);




app.get('/', function(req, res){
  res.send('hello world');
});


   
app.listen(process.env.Port|| 3000, () => {
    console.log("Server has started on Port 3000");

});


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source