1

I am working on to make REST API in express js but getting an error "Cannot GET /api/bears". here is my code

server.js

var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var Bear = require('./app/models/bear'); mongoose.connect('mongodb://localhost/api', { useNewUrlParser: true }); // connect to our database app.use(bodyParser.urlencoded({ extended: true})); app.use(bodyParser.json()); var port = process.env.PORT || 3000; //routes for api var router = express.Router(); router.use(function(req, res, next) { console.log('Something is happening.'); next(); }); router.get('/',function(req,res){ res.json({message: "Welcome to my Api"}); }); router.route('/bears') .post(function(req,res){ var bear = new Bear(); bear.name = req.body.name; bear.save(function(err){ if(err) { res.send(err); } res.json({message: 'bear created!'}); }); }); app.use('/api', router); app.listen(port); console.log("Magic happens on port" + port); 

app/models/bear.js

var mongoose = require('mongoose'); var Schema = mongoose.Schema; var BearSchema = new Schema({ name: String }); module.exports = mongoose.model('Bear', BearSchema); 

On localhost:3000/api, everything works fine but on localhost:3000/api/bears I am getting Cannot GET /api/bears

Could anyone help me where I am missing?

2 Answers 2

3

You will certainly get this error

Cannot GET /api/bears

The second word is important here : GET

You defined your route with :

router.route('/bears').post(function(req,res){ [...] }) 

If you send a GET request, you will certainly not match a route. Make a POST request instead.

Sign up to request clarification or add additional context in comments.

Comments

1

You have created route with POST method to create bear but don't have route for getting the data:

router.route('/bears').post(function..... 

That's why you are getting:

400 Cannot GET /api/bears

Add something like this and try again.

router.route('/bears').get(function (req, res) { Bear.find({}, function (err, result) { res.status(200).send({ result }); }) }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.