'Performing a HTTP POST request in Node with MongoDB/Mongoose?
I have defined my schema, I just need to know the syntax to do the actual HTTP POST request. I am using MongoDB with Mongoose framework. This way when I go to my localhost:300/users I can see my JSON data posted.
The JSON data I want to post to my localhost:3000/users
{
"firstName": "Jono",
"lastName": "Ganesan",
"email": "[email protected]",
"username": "username",
"password": "password"
}
my server.js file
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);
};
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);
}
});
};
Solution 1:[1]
As I understood - you want to know the syntax of making post request to add user. On client side, using jQuery - you can make a server POST request using this code:
$.post("http://localhost:300/users", {
"firstName": "Jono",
"lastName": "Ganesan",
"email": "[email protected]",
"username": "username",
"password": "password"
} ,
function(data, status){
alert("Data: " + data);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nitin Jadhav |