我已經(jīng)從nodejs開(kāi)始,并一直嘗試使用axios在post api中發(fā)送數(shù)據(jù),但沒(méi)有在服務(wù)器端獲取它,這是我的設(shè)置客戶(hù)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>); }}服務(wù)器端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)產(chǎn)品routes.js 文件const express = require('express');const productController = require('../controllers/product');const router = express.Router();router.post('/add-product', productController.addProduct);module.exports=router控制器文件 exports.addProduct = (req, res, next) => {console.log(req.body) //gives me {} everytime }在這里,我每次從客戶(hù)端發(fā)送一個(gè)對(duì)象,我將 {} 視為控制臺(tái)我的兩個(gè)項(xiàng)目分別運(yùn)行在 localhost:3000 和 5000 上
發(fā)送的 axios post api 數(shù)據(jù)在服務(wù)器端的 console.log(req.body)
婷婷同學(xué)_
2023-07-14 16:13:14