简体   繁体   English

发送的 axios post api 数据在服务器端的 console.log(req.body) 上给出了空对象

[英]axios post api data sent gives empty object on console.log(req.body) on server side

I have started with nodejs and have been trying to send data in the post api using axios but not getting it in the server side here is my setup我已经开始使用 nodejs 并且一直尝试使用 axios 在 post api 中发送数据,但没有在服务器端获取它,这是我的设置

CLIENT客户

export default class App extends Component {
  componentDidMount() {
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': 'JWT fefege...'
    }
    let data = { title: "abc", price: 20 }; // i am sending this data 
    axios
      .post("http://localhost:5000/add-product", data, {
        headers: headers,
      })
      .then((res) => console.log(res))
      .catch((err) => console.log(err));
  }
 
  render() {
    return (<div></div>);
  }
}

SERVERS SIDE服务器端

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
let cors = require("cors");
const productRoutes = require("./routes/product");
app.use(cors());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(productRoutes);
app.listen(5000)

products routes.js file产品 routes.js 文件

const express = require('express');

const productController = require('../controllers/product');

const router = express.Router();
router.post('/add-product', productController.addProduct);
module.exports=router

controller file控制器文件

 exports.addProduct = (req, res, next) => {
console.log(req.body) //gives me {} everytime
 }

here eveytime i send an object from client side i see {} as console在这里,我每次都从客户端发送一个对象,我将 {} 视为控制台

Both my projects runs on localhost:3000 and 5000 respectively我的两个项目分别在 localhost:3000 和 5000 上运行

添加

app.use(bodyParser.json());

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

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