Node.js POST service to a database

I just created a web service that I can use to POST data and insert the data into a database.

Here's the code from my server.js, which is an express app:


var history = require('./routes/history');
...
app.post('/history', history.create);

I have a route called history.js which services this route:


exports.create = function(req, res) {

console.log("Create the history");
console.log(JSON.stringify(req.body));
// Sequelize does the db insert here.
rm.BaseHistory.build(req.body).save();
res.send("ok");
};



This is a very crude example with no real error handling, but you get the point.  The variable "req.body" has the "post data".  Now I can submit data via curl like this:


$ ./create-history-test.sh
+ curl -X POST -H 'Content-Type: application/json' --data @hist.json http://mycomputer.domain.com:40000/history

I have a separate file in the same directory called hist.json which has a json object of the same model as my Sequelize table.

In the node application log you will see:


Create the history
{"blah1":"a","blah2":"a"}
[90mPOST /history [32m200 [90m17ms - 2 [0m
Executing: INSERT INTO `BaseHistories` (`blah1`,`blah1`) VALUES ('a','b');

This blog post assumes you have node, express and sequelize set up.  Happy databasing!

Comments

Popular Posts