简体   繁体   中英

req.body is empy {} when using http. post in angular and node.js

This is my service.ts file

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Items } from "./inventory.model";
import { Router } from "@angular/router";


import { environment } from "../../../environments/environment";
const BACKEND_URL = environment.APIUrl + "/Items/";

@Injectable({
providedIn: "root",
})
export class InventoryService {
constructor(private http: HttpClient, private router: Router) {}

addItem(
itemNo: string,
itemName: string,
maker: string,
unitPrize: string,
sellingPrize: string,
Qty: string
) {



const ItemData = new FormData();
ItemData.append("itemNo", itemNo);
ItemData.append("item_name", itemName);
ItemData.append("maker", maker);
ItemData.append("unitPrize", unitPrize);
ItemData.append("sellingPrize", sellingPrize);
ItemData.append("Qty", Qty);


  this.http
  .post<{ message: string; items: Items }>(
    BACKEND_URL,
    ItemData
  )
  .subscribe((responseData) => {

     console.log(responseData);


  });

  }
  }

This is my item.js in back-end routes

const express = require("express");
const ItemController = require("../controllers/item");
const bodyParser = require('body-parser');
const router = express.Router();

router.post("", ItemController.savepost);

This is my Item.js file in Controller

    const ItemModel = require('../models/item');

exports.savepost = (req, res, next) => {

  if(Object.keys(req.body).length === 0)
  {
    console.log(req.body);
  }


  const items = new ItemModel({

    item_no: req.body.itemNo,
    item_name: req.body.itemName,
    maker: req.body.maker,
    unitPrize: req.body.unitPrize,
    sellingPrice: req.body.sellingPrize,
    Qty: req.body.Qty,


  });


  console.log(items.item_no);


  items.save().then(addItem => {
        res.status(201).json({
          message: "Item added Successfully",
          items: {
            ...addItem,
            id: addItem._id
          }
        });
  }).catch(error => {

  res.status(500).json({

    message: error
  })
}
);

}

THis is my Item model

const mongoose = require('mongoose');

const itemSchema = new mongoose.Schema({

  item_no: { type: String, required: true },
  item_name: { type: String, required: true },
  maker: { type: String, required: true },
  unitPrize: { type: Number, required: true },
  sellingPrice: { type: Number, required: true },
  Qty: { type: Number, required: true },



});

module.exports = mongoose.model('Items',itemSchema);

Response error shows message like this

Items validation failed", message: "Items validation failed: item_no: Path item_no is required., item_name: Path item_name is required., maker: Path maker is required., unitPrize: Path unitPrize is required., sellingPrice: Path sellingPrice is required., Qty: Path Qty is required.",

put / in your route

router.post("/", ItemController.savepost);

use this code in app.js because you don't parse req.body

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

please try following code

const ItemData =  {
  itemNo,
  item_name,
  maker,
  unitPrize,
  sellingPrize,
  Qty
}
const headers = { 'content-type': 'application/json'}  
const body=JSON.stringify(ItemData);
this.http.post<{ message: string; items: Items }>(BACKEND_URL, body,{'headers':headers}).subscribe((responseData) => {
  console.log(responseData);
});

I tested backend code, and it's right, the problem is about post request in frontend code, you can check the post request docomentation

you send your Object data without parsing in JSON format. so before sending the request first convert it to a pure JSON. you can achieve this after adding this code in the app.js file.

app.use(bodyParser.json());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM