问题描述
我正在尝试将 post 函数中请求正文的内容打印到控制台,如下所示:
export const createOffering = async (req,res) => {
const offering = req.body;
const newOffering = new Offering(offering);
console.log(req.body);
try{
//await offering.save();
res.status(201).json(newOffering);
}
catch(error){
res.status(409).json({message: error.message})
}
}
然而,控制台打印“未定义”
这是我的 index.js 的代码
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import bodyParser from "body-parser";
import offeringsRoutes from './routes/offerings.js'
const app = express();
app.use('/offerings',offeringsRoutes);
app.use(cors());
app.use(express.urlencoded({ limit: '25mb',extended: true }));
app.use(express.json({ limit: '25mb' }));
解决方法
app.use
通常用于要在路由之前运行的中间件。我还看到您导入了 bodyParser
但不使用它,虽然这不是必需的,但您可能希望重构的方式如下:
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import bodyParser from "body-parser";
import offeringsRoutes from './routes/offerings.js'
const app = express();
// You generally want this middleware above your routes if you want
// them to apply to all routes that come after these.
app.use(cors());
app.use(express.urlencoded({ limit: '25mb',extended: true }));
app.use(express.json({ limit: '25mb' }));
app.use(bodyParser.json());
// If you only want to accept `POST` requests
app.post('/offerings',offeringsRoutes);
// or you can use this if you want this function to handle all requests to this route
// app.all('/offerings',offeringsRoutes);