gpt4 book ai didi

javascript - 无法在帖子响应中读取正文 [express.js]

转载 作者:行者123 更新时间:2023-11-29 21:07:01 27 4
gpt4 key购买 nike

我正在使用 chrome 中的 ReSTLet 客户端工具发出发布请求。在 console.log(res) 中,我可以清楚地看到那里有 body,数据完全正确,但我仍然总是收到一条错误消息,说在执行 res.body 时 body is undefined。

这是代码

var express = require('express');
var parser = require('body-parser');
var mongoose = require('mongoose');

var app = express();

app.use(parser.urlencoded({extended: true}));
app.use(parser.json());

var db = mongoose.connection;

var port = process.env.PORT || 8000;

var router = express.Router();

router.use(function(req, res, next) {
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});

router.get('/',function(req,res){
res.json({msg: 'Welcome to Pre-Health API!'});
});

var User = mongoose.Schema({
first_name: String,
last_name: String
},{
collection: 'User',
timestamps: true
});

router.route('/user').post(function(res,req) {
var user = mongoose.model('user',User);
console.log(req);
var new_user = new user({
first_name: req.body.first_name,
last_name: req.body.last_name
});

user.save(function(err) {
if(err) res.send(err);
res.json({message: "User created"});
});
});

app.use('/api',router);

app.listen(port);
console.log('API Listening on port: ' + port);

最佳答案

在你有reqres反转的函数中,它应该是:

router.route('/user').post(function(req, res) { ...

关于javascript - 无法在帖子响应中读取正文 [express.js],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43533310/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com