I've implemented the following code in my Express
application:
var express = require('express'); // Initializing Express
var app = express(); // Creating our app using Express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
// Connecting to the database
mongoose.connect('mongodb://username:pwd@<url>/db-name');
var Bear = require('./app/models/bear');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // Setting up the port
var router = express.Router();
// Middleware for all requests
router.use(function(req, res, next) {
// Logging
console.log('Something is happening.');
next(); // Proceeding to the next route
});
router.route('/bears')
.get(function(req, res) {
Bear.find(function(err, bears) {
if(err)
res.send(err);
console.log('I am in GET');
res.json(bears);
});
})
.post(function(req, res) {
var bear = new Bear();
bear.name = req.body.name;
console.log('Body Param:'+ bear.name);
bear.save(function(err) {
if(err)
res.send(err);
res.json({ message: 'Bear created!'});
});
});
router.get('/', function(req, res) {
res.json({ message: 'Hooray! Welcome to our API!' });
});
app.use('/api', router);
app.listen(port);
Here is my Model
code:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
When I make a request using POSTMAN or the browser, it keeps loading indefinitely without returning anything. I believe the callback needs to be terminated but I'm not sure how to do that.
The URL I'm accessing is http://localhost:8080/api/bears
and the request doesn't seem to complete.
Server output when hitting /api/bears and the request stalls:
Something is happening.
Output from server when visiting /api
Something is happening.
And on the browser, I see:
Cannot GET /api