[英]TypeError: Cannot read property 'username' of undefined--
var express = require("express"); var app = express(); var morgan = require("morgan"); var mongoose = require("mongoose"); port = 8000; var User = require("./app/models/user"); mongoose.connect("mongodb://localhost:27017/tutorial", function (err) { if (err) { console.log("Disconnected: " + err); } else { console.log("connected"); } }); app.post("/users", function (req, res) { var user = new User(); user.username = req.body.username; user.email = req.body.email; user.password = req.body.password; user.save(); res.send("user created"); }); app.use(morgan("dev")); app.listen(port, function () { console.log("You are listen on port " + port); });
Include a code to grab the request body using express method express.json which uses body parser module behind the scenes Eg包含一个代码来使用快速方法 express.json 获取请求正文,该方法在幕后使用正文解析器模块 例如
This should work这应该工作
app.use(express.json()) app.use(express.json())
If your post request comes as json as I presume it does you are going to need to somehow parse the request's body.如果您的帖子请求像我认为的那样以 json 形式出现,那么您将需要以某种方式解析请求的正文。 You can do that by requiring "body-parser" and using it's json method like so:
您可以通过要求“body-parser”并使用它的 json 方法来做到这一点,如下所示:
const bodyParser = require('body-parser');
const app = require('express')();
app.use(bodyParser.json());
What we're saying with app.use(bodyParser.json())
is to use that body parser for every single route.我们对
app.use(bodyParser.json())
是为每条路线使用该正文解析器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.