'Why am I getting "Cannot read property 'payload ' of undefined"

I'm developing and application for search, when the user types in the input box a post request is sent to check the data base(mongoose) to see if it exist, if it does the response sends back the payload to the client with names that match. When I type into box I get UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'payload' of undefined from the server. In the chrome development tool the status is pending. From my research the req.body.payload in which body is the property. I have the added app.use(express.json() and I have even tried const bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: false })) 

app.use(bodyParser.json()). When adding a dummy handler on my route I do get the request from the client with a status of 200. Here is a code snippet.

My server.js

const press.Router();
const someProducts      = require('./liveSearch');
const getProducts        = 
require('.../../controllers/api/getProducts/getProducts')



const mongoose = require('mongoose');

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(express.json());
  app.use(express.urlencoded({extended: true}));
  
      

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

});



const app = express();

app.options('/getProducts', cors()) // enable pre-flight 
app.use(cors({
  origin: [
    'http://localhost:4200'           ]
}))

 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");

});

module.exports = router

 
  

my getProducts.js
var express = require('express');
const cors    = require('cors');
const someProducts      = require('../liveSearch');
var router = express.Router();

const bodyParser = require('body-parser')
const app = express();


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false })) 

// parse application/json
app.use(bodyParser.json())


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

  
router.post('/getProducts', async(req,res) =>{
   console.log("Does it get to post");
   payload: req.body.payload;
   console.log("does it get pass")
   let search = await someProducts.find({name: {$regex: new RegExp('^'+payload+'.*',
   'i')}}).exec();
      //Limit search to 10
   search = search.slice(0, 10);
   //res.send("got a post request")
   res.send({payload:payload});
})



//export this router to use in our server.js
module.exports = router;

My post request is in my searchservice.ts

import { Injectable } from '@angular/core';
import{HttpClient, HttpHeaders} from '@angular/common/http';
import{map, catchError, tap} from 'rxjs/operators'
//import { Product } from '@app/models/product';
import { Observable } from 'rxjs';
import {MessengerService} from 'src/app/services/messenger.service';
import {productsUrl} from '@app/ui/header/api'
import { productUrl } from '@app/config/api';


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


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


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

    
Thanking You in Advance.
PH


Solution 1:[1]

I moved the app.use(express.json()); app.use(express.urlencoded({extended: true}));

more towards the bottom of the file where my app.use('/', getProducts) app.use('/getProducts', getProducts);

and the eror went away.

PDH

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 user2280852