1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
// Load required packages var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); // Connect to the beerlocker MongoDB mongoose.connect('mongodb://localhost/beerlocker'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function (callback) { console.log('mongoose db connected'); }); // Create our Express application var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Use environment defined port or 3000 var port = process.env.PORT || 3000; // Create our Express router var router = express.Router(); // http://localhost:3000/api GET router.get('/', function(req, res) { console.log("GET /api/ "); //console.dir(req.body); //console.dir(req.params); console.dir(req.query); // when using GET and key/value is attached to the url res.json({ message: 'You are running dangerously low on beer!' }); }); // http://localhost:3000/api POST router.post('/', function(req, res) { console.log("POST /api/ "); console.dir(req.body); //make sure you use x-www-form-urlencoded //console.dir(req.params); //console.dir(req.query); res.json({ message: 'You are running dangerously low on beer!' }); }); // Register all our routes with /api app.use('/api', router); // Start the server app.listen(port); console.log('Insert beer on port ' + port); |
start up your server
> node server.js
Then the output from the terminal would be like this:
Insert beer on port 3000
mongoose db connected
Use postman to send data
Make sure you select POST as your request verb.
type in the test url:
http://localhost:3000/api/
Select Body, because we are using POST data from a web form.
The body data comes from a x-www-form-urlencoded
For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string — name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:
MyVariableOne=ValueOne&MyVariableTwo=ValueTwo
This query string is stored in the BODY of the message packet.
So in POSTMAN, just put test as the key, and please work as the value.
When you press “Send” in POSTMAN, you should see the output from your node terminal like so:
POST /api/
{ test: ‘please work’ }
{}
{}
As you can see, the results appear in req.body