我构建了一个代码来创建一个带有node.js,express.js和mongodb的服务器。 这是一个将用户数据保存到mongodb的简单代码。我使用高级REST客户端测试了此代码。
此时,请求参数已传输,但在使用此URL发送请求时出现0请求错误:http://localhost:8080/users。
server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var morgan = require('morgan');
var mongoose = require('mongoose');
var User = require('./user');
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(morgan('dev'));
mongoose.createConnection('mongodb://localhost:27017/mean', function(err) {
if (err) {
console.log('Not connected to the database: ' + err);
} else {
console.log('Successfully connected to MongoDB')
}
});
// http://localhost:8080/users
app.post('/users', function(req, res) {
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.email = req.body.email;
if (req.body.username == null || req.body.username == "" || req.body.password == null || req.body.password == "" || req.body.email == null || req.body.email == "") {
res.send("Ensure username, email and password were provided");
} else {
user.save(function(err) {
if (err) {
res.send("Username or Email already exists.");
} else {
res.send("user created");
}
});
}
});
app.listen(port, function() {
console.log('Running the server on port ' + port);
});
user.js的
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema({
username: { type: String, lowercase: true, required: true, unique: true },
password: { type: String, required: true },
email: { type: String, required: true, lowercase: true, unique: true }
});
UserSchema.pre('save', function(next) {
var user = this;
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
module.exports = mongoose.model('User', UserSchema);
的package.json
{
"name": "mean",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "^2.18.2",
"express": "^4.16.2",
"mongoose": "^4.13.7",
"morgan": "^1.9.0"
}
}
答案 0 :(得分:1)
您应该使用浏览器执行post
请求而不是get
请求。
另外
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.email = req.body.email;
if (req.body.username == null || req.body.username == "" || req.body.password == null || req.body.password == "" || req.body.email == null || req.body.email == "") {
res.send("Ensure username, email and password were provided");
您未在请求中发送email
或name
,......等参数。因此,您的数据库中无法保存任何内容。
执行post
请求而不是get
并考虑在您的请求中添加正确的参数,一切都会好的。
答案 1 :(得分:0)