Created
November 4, 2014 10:06
-
-
Save yumu19/744c27c930aa1a13b536 to your computer and use it in GitHub Desktop.
node.js file which saves body of HTTP POST to MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var mongoose = require('mongoose'); | |
var Schema = mongoose.Schema; | |
var dataSchema = new Schema({ data: Schema.Types.Mixed}); | |
var Data = mongoose.model('data', dataSchema); | |
mongoose.connect('mongodb://localhost/test'); | |
http.createServer(function (req, res) { | |
if(req.method=='POST') { | |
var body = ''; | |
req.on('data', function (dat) { | |
body +=dat; | |
}); | |
req.on('end',function(){ | |
var doc = new Data({ data: JSON.parse(body) }); | |
doc.save(function(err){ | |
if(err) { | |
console.log(err); | |
} else { | |
console.log(body); | |
} | |
}); | |
res.writeHead(200, {'Content-Type':'application/json; charset=utf-8'}); | |
res.end('{"result":"ok"}'); | |
}); | |
} | |
}).listen(1337, "localhost"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment