使用MongoDB / Mongoose在Node中执行HTTP POST请求?

时间:2015-05-07 04:46:26

标签: javascript json node.js mongodb

我已经定义了我的架构,我只需要知道执行实际HTTP POST请求的语法。我正在使用MongoDB和Mongoose框架。这样当我去我的本地主机:300 /用户时,我可以看到我发布的JSON数据。

我想发布到我的localhost的JSON数据:3000 / users



{ 
  "firstName": "Jono", 
  "lastName": "Ganesan", 
  "email": "user@example.com", 
  "username": "username", 
  "password": "password" 
} 




我的server.js文件



process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var mongoose = require('./config/mongoose');
var express = require('./config/express');
var db = mongoose();
var app = express();
app.listen(3000);
module.exports = app;
console.log('Server running at http://localhost:3000/');




user.server.model.js



var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
var UserSchema = new Schema({
    firstName: String,
    lastName: String,
    email: String,
    username: String,
    password: String
});
mongoose.model('User', UserSchema);




user.server.routes.js



var users = require('../../app/controllers/users.server.controller');
module.exports = function(app) {
    app.route('/users').post(users.create);
};



 user.server.controller



var User = require('mongoose').model('User');
exports.create = function(req, res, next) {
    var user = new User(req.body);
    user.save(function(err) {
        if (err) {
            return next(err);
        } else {
            res.json(user);
        }
    });
};




1 个答案:

答案 0 :(得分:0)

据我所知 - 你想知道发布请求添加用户的语法。 在客户端,使用jQuery - 您可以使用以下代码发出服务器POST请求:

$.post("http://localhost:300/users", { 
  "firstName": "Jono", 
  "lastName": "Ganesan", 
  "email": "user@example.com", 
  "username": "username", 
  "password": "password" 
} ,
 function(data, status){
        alert("Data: " + data);
});