简体   繁体   English

使用 http 时,req.body 为 empy {}。 发布在 angular 和 node.js

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

This is my service.ts file这是我的 service.ts 文件

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这是我在后端路由中的 item.js

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这是我在 Controller 中的 Item.js 文件

    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这是我的项目 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); 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.",商品验证失败”,消息:“商品验证失败:item_no:需要路径item_no 。,item_name:需要路径item_name 。,maker:需要路径maker 。,unitPrize:需要路径unitPrize 。, sellPrice:需要路径sellingPrice ., 数量:路径Qty是必需的。",

put / in your route/放在你的路线上

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

use this code in app.js because you don't parse req.body在 app.js 中使用此代码,因为您不解析 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我测试了后端代码,没错,问题是前端代码中的post request,你可以查看post request 文档

you send your Object data without parsing in JSON format.您发送 Object 数据而不以 JSON 格式进行解析。 so before sending the request first convert it to a pure JSON.所以在发送请求之前首先将其转换为纯 JSON。 you can achieve this after adding this code in the app.js file.您可以在 app.js 文件中添加此代码后实现此目的。

app.use(bodyParser.json());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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