Express routes returning 404s - javascript

I have a couple of simple routes that I have misconfigured and not sure why.
app.js:
//app setup
var http = require('http');
var bodyParser = require('body-parser');
var express = require('express');
var routes = require('./routes');
var agent = require('./routes/agent');
var config = require('./config');
var app = express();
app.server = http.createServer(app);
app.use(bodyParser.json({
limit : config.bodyLimit
}));
app.use(bodyParser.urlencoded({
extended : true
}));
app.use('/v1', routes);
app.use('/v1/agent', agent);
app.server.listen(config.port);
console.log('API listening on port ' + app.server.address().port);
module.exports = app;
This returns responses on the /v1/ route (index.js):
'use strict';
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.status(403).json({
message: 'Invalid request.'
});
});
module.exports = router;
in the agent route, I have a POST handler that is being handled correctly at /v1/agent/login. But while a GET routed at /v1/agent/ works, a GET routed to /v1/agent/123 returns a 404:
'use strict';
var agentController = require('../controller/agent.js');
var express = require('express');
var router = express.Router();
function handleError(objError, res) {
res.status(500).json({ errorMessage : objError.message });
}
router.get('/', function (req, res) {
res.status(200).json({
message: 'OK' // works fine
});
});
router.get('/:id'), function (req, res) {
var agentNum = req.params.id;
res.send(req.params); // 404 here
try {
//res.status(200).json({ message: 'hello agent.'});
} catch (err) {
// handleError(err, res);
}
};
router.post('/login', function (req, res) {
var agentNum, password;
// works fine
});
router.post('/pwr', function (req, res) {
//also works fine
});
module.exports = router;
My understanding is that the app.use method should redirect the route and any GET requests appended to that route to the one I specified (agent), so why is it that the one with params fails while the root one succeeds?
Thank you

You're not passing the callback correctly.
router.get('/:id')
router.get('/:id', function(req, res) {
var agentNum = req.params.id;
res.send(req.params); // 404 here
try {
//res.status(200).json({ message: 'hello agent.'});
} catch (err) {
// handleError(err, res);
}
});

Related

Problem in APIRest file throught GET in node.js

I am trying to do my first API Rest and I am following some tutorials. I am requesting all the articles in a MongoDB database.
This is the code of the main:
var express = require("express"),
app = express(),
http = require("http"),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
server = http.createServer(app),
mongoose = require('mongoose');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
// Import Models and controllers
var models = require('./models/article')(app, mongoose);
var articleCtrl = require('./controllers/articleController');
// Example Route
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
articles.route('/articles/:id')
.get(articleCtrl.findById);
articles.route('/articles')
.get(articleCtrl.findAllarticles)
.post(articleCtrl.addarticle);
app.use('/api', articles);
app.use(router);
mongoose.connect('mongodb://localhost/ustcg', { useNewUrlParser: true ,useUnifiedTopology: true}, function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
});
The code of the controller is here:
// Import article and mongoose
var mongoose = require('mongoose');
var Article = mongoose.model('Article');
//GET - Return a article with specified ID
exports.findById = function(req, res) {
Article.findById(req.params.id, function(err, Article) {
if(err) return res.send(500, err.message);
console.log('GET /article/' + req.params.id);
res.status(200).jsonp(Article);
});
};
//GET - Return all articles in the DB
exports.findAllarticles = function(req, res) {
Article.find(function(err, Article) {
if(err) res.send(500, err.message);
console.log('GET /article')
res.status(200).jsonp(Article);
});
};
//POST - Insert a new article in the DB
exports.addarticle = function(req, res) {
console.log('POST');
console.log(req.body);
var Article = new Article({
title: req.body.title,
paragraphs: req.body.paragraphs
});
Article.save(function(err, Article) {
if(err) return res.send(500, err.message);
res.status(200).jsonp(Article);
});
};
The model:
//We create the model
exports = module.exports = function(app, mongoose) {
var ArticleSchema = new mongoose.Schema({
title: { type: String },
paragraphs: { type: Array },
});
mongoose.model('Article', ArticleSchema);
};
When I tried to request the following http request it send me 404 error. I can not see any logs on the console so it is not entering the methods in order to see the exception is happening so I am stucked with this...
If someone could help me it would be nice.
what is articles variable in your main file.
I tried your code in my machine and struggled with articles variable and you have extra imports which are not required.
Try following code it works fine
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var articleCtrl = require('./sample.controller');
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
router.get('/articles/:id', articleCtrl.findById);
router.post('/articles', articleCtrl.addarticle);
router.get('/articles', articleCtrl.findAllarticles)
// app.use('/api', router);
app.use(router);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
if you uncomment app.use('/api', router); then you can also use routes as localhost:3000/api/articles

Error when exporting socket.io variable in ExpressJs server

I would create a data stream , so when I trigger post route , get route fetch new data.
So I'm using Socket.io to do that .
first I have a problem when exporting io variable from server.js to Nouvproj.js
in my server.js file :
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require("express"); // call express
var app = express();
var bodyParser = require("body-parser");
var port = process.env.PORT || 8081; // set our port
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT ,DELETE");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get("/", function(req, res) {
res.sendFile(__dirname + "../src/index.html");
});
var server = app.listen(port);
var io = require("socket.io").listen(server);
// define our app using express
var routerProj = require("./routes/ajoutProj")(io);
app.use("/api/proj", routerProj);
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017", {
useMongoClient: true
/* other options */
}); // connect to our database
mongoose.connection.on("error", function(error) {
console.log("error", error);
});
// Chargement de socket.io
// Quand un client se connecte, on le note dans la console
// START THE SERVER
// =============================================================================
io.sockets.on("connection", function(socket) {
console.log("socket");
});
then in my rooutes I import the variable . and use emit and on function to create the stream.
// ROUTES FOR OUR API
var express = require("express"); // call express
var NouvProj = require("../app/models/nouvProj");
var mongoose = require("mongoose");
var Soc = require("../server");
var io = Soc.io;
var router = express.Router(); // get an instance of the express Router
router.use(function(req, res, next) {
// do logging
console.log("Something is happening.");
next(); // make sure we go to the next routes and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
module.exports = function(io) {
router
.route("/projets")
// create a nouvProj (accessed at POST http://localhost:8080/api/nouvProjs)
.post(function(req, res) {
var nouvProj = new NouvProj();
// create a new instance of the nouvProj model
nouvProj.nomProj = req.body.nomProj;
nouvProj.leadProj = req.body.leadProj;
nouvProj.descProj = req.body.descProj;
nouvProj.BesProj = req.body.BesProj;
nouvProj.pers = req.body.pers;
nouvProj.backlog.fonctionnalite = req.body.Fonctionnalite;
nouvProj.backlog.userStory = req.body.UserStory;
// save the nouvProj and check for errors
nouvProj.save(function(err) {
if (err) {
res.send(err);
console.log("err");
}
res.json({
message: "nouvProj created!"
});
io.sockets.emit("added", function() {
console.log("Un projet est ajouté !");
});
});
})
.get(function(req, res) {
NouvProj.find(function(err, nouvProjs) {
if (err) res.send(err);
else {
io.sockets.on("added", function() {
res.json(nouvProjs);
});
}
});
});
router.get("/", function(req, res) {
res.json({
message: "hooray! welcome to our api!"
});
});
}
// more routes for our API will happen here
module.exports = router;
Then I get this error
TypeError: Cannot read property 'sockets' of undefined
so Nouvproj.js is not getting the content of the variable so that I could work with socket.io in this file.
Update: I have updated my files as you described now I'm having this error :
return fn.apply(this, arguments);
^
TypeError: Cannot read property 'apply' of undefined
You always get undefined socket when you want exported socket module.
You can do this issue like this
for your use, you can use process core module of nodejs here is
link
// ROUTES FOR OUR API
var express = require("express"); // call express
var NouvProj = require("../app/models/nouvProj");
var mongoose = require("mongoose");
var router = express.Router(); // get an instance of the express Router
router.use(function(req, res, next) {
// do logging
console.log("Something is happening.");
next(); // make sure we go to the next routes and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router
.route("/projets")
// create a nouvProj (accessed at POST http://localhost:8080/api/nouvProjs)
.post(function(req, res) {
var nouvProj = new NouvProj();
// create a new instance of the nouvProj model
nouvProj.nomProj = req.body.nomProj;
nouvProj.leadProj = req.body.leadProj;
nouvProj.descProj = req.body.descProj;
nouvProj.BesProj = req.body.BesProj;
nouvProj.pers = req.body.pers;
nouvProj.backlog.fonctionnalite = req.body.Fonctionnalite;
nouvProj.backlog.userStory = req.body.UserStory;
// ROUTES FOR OUR API
var express = require("express"); // call express
var NouvProj = require("../app/models/nouvProj");
var mongoose = require("mongoose");
var Soc = require("../server");
var io = Soc.io;
var router = express.Router(); // get an instance of the express Router
router.use(function(req, res, next) {
// do logging
console.log("Something is happening.");
next(); // make sure we go to the next routes and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router
.route("/projets")
// create a nouvProj (accessed at POST http://localhost:8080/api/nouvProjs)
.post(function(req, res) {
var nouvProj = new NouvProj();
// create a new instance of the nouvProj model
nouvProj.nomProj = req.body.nomProj;
nouvProj.leadProj = req.body.leadProj;
nouvProj.descProj = req.body.descProj;
nouvProj.BesProj = req.body.BesProj;
nouvProj.pers = req.body.pers;
nouvProj.backlog.fonctionnalite = req.body.Fonctionnalite;
nouvProj.backlog.userStory = req.body.UserStory;
// save the nouvProj and check for errors
nouvProj.save(function(err) {
if (err) {
res.send(err);
console.log("err");
}
res.json({
message: "nouvProj created!"
});
process.emit("added", function() {
console.log("Un projet est ajouté !");
});
});
})
.get(function(req, res) {
NouvProj.find(function(err, nouvProjs) {
if (err) res.send(err);
else {
process.on("added", function() {
res.json(nouvProjs);
});
}
});
});
router.get("/", function(req, res) {
res.json({
message: "hooray! welcome to our api!"
});
});
// more routes for our API will happen here
module.exports = router;
// save the nouvProj and check for errors
nouvProj.save(function(err) {
if (err) {
res.send(err);
console.log("err");
}
res.json({
message: "nouvProj created!"
});
process.emit("added", function() {
console.log("Un projet est ajouté !");
});
});
})
.get(function(req, res) {
NouvProj.find(function(err, nouvProjs) {
if (err) res.send(err);
else {
process.on("added", function() {
res.json(nouvProjs);
});
}
});
});
router.get("/", function(req, res) {
res.json({
message: "hooray! welcome to our api!"
});
});
// more routes for our API will happen here
module.exports = router;
You can pass io like this:
projects.js -file
var express = require("express");
var router = express.Router();
module.exports = function (io) {
router.get('/something', ..., function (req, res) {
io.sockets.on('connection', function (socket) {
... do something
})
})
}
server.js -file
var express = require("express"); // call express
var app = express();
var bodyParser = require("body-parser");
...
...
var server = app.listen(port)
var io = require("socket.io").listen(server);
var projects = require('./routes/projects')(io);
app.use('/projects', projects);
...

Node.js restful webservice using express and mongoose. Routing not working

I'm trying to build a RESTful webservice following this tutorial:
https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd
It's not working returning me a CANNOT GET/ reports error...
I'm trying to learn node.js and I can't find the error anywhere and everything I tried didn't work.
Also, when I call the server, it reaches to index.js which prints a "HEY". Wasn't this supposed to reach server.js first?
Here is my code:
Server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Report = require('./api/models/reportModel.js'),
bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/server');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/reportRoute.js');
routes(app);
app.listen(port);
console.log('Report RESTful API server started on: ' + port);
reportRoute.js
'use strict';
module.exports = function(app) {
var reports = require('../controllers/reportController.js');
// report Routes
app.route('/reports')
.get(reports.list_all_reports)
.post(reports.create_a_report);
app.route('/reports/:reportId').get(reports.read_a_report)
.put(reports.update_a_report)
.delete(reports.delete_a_report);
};
reportController.js
'use strict';
var mongoose = require('mongoose'),
Report = mongoose.model('Reports');
exports.list_all_reports = function(req, res) {
Report.find({}, function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.create_a_report = function(req, res) {
var new_report = new Report(req.body);
new_report.save(function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.read_a_report = function(req, res) {
Report.findById(req.params.reportId, function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.update_a_report = function(req, report) {
Report.findOneAndUpdate({_id: req.params.taskId}, req.body, { new: true }, function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.delete_a_report = function(req, res) {
Report.remove({
_id: req.params.reportId
}, function(err, report) {
if (err)
res.send(err);
res.json({ message: 'Report successfully deleted' });
});
};
Thank you for your help...
EDIT:
index.js
const express = require('express');
const app = express();
var route = require('./api/routes/reportRoute');
app.get('/', function(req, res) {
res.send('HEY!');
})
app.listen(3000, function(){console.log('Server running on port 3000')});
You haven't posted your reportController.js but this problem will occur if the function list_all_reports does not set a response body. For example, adding
res.json({hello: "world"});
to the handler function should make it work.

MongoDB - TypeError: users.aggregate is not a function

I'm trying to query a collection using aggregate but getting TypeError: users.aggregate is not a function. Here's my code:
./app.js (reduced to fit)
var express = require('express');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/mydb');
var users = require('./routes/users');
var app = express();
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use('/users', users);
module.exports = app;
./routes/users.js
var express = require('express');
var router = express.Router();
router.get('/test', function(req, res) {
var users = req.db.get('users');
users.aggregate([{ $match: { username: 'test0' }}], function(err, data) {
res.json(data);
});
});
module.exports = router;
I'm running MongoDB version 3.2.10 and the above query works fine in the console. I've looked up solutions and they all suggest to check the MongoDB version, which I've already done. I've also tried req.db.collection('users').aggregate (as suggested by another post) and receive a similar error: req.db.collection is not a function. What am I missing?
EDIT:
Running users.find({ username: 'test0' }, func... works and returns correct data.
EDIT2: Added more code.
You can do like this.
var app = require('express')();
var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('mongodb://localhost/test'));
app.get('/', function (req, res, next) {
req.db // => Db object
});
I tried with this. It is working in my local.
var app = require('express')();
const db = require('monk')('localhost/test')
app.use(function(req,res,next){
req.db = db;
next();
});
app.get('/', function (req, res, next) {
var db = req.db;
var users = db.get('users');
users.aggregate([
{$match: { firstName: 'Test 2' }}
]).then(function(docs) {
console.log(docs)
})
});
app.listen(3010, function () {
console.log('Example app listening on port 3010!');
});

Express.js req.body is returning nothing

I am learning node and express to create an api for an angular app I will be creating.
When I try and post something the req.body seems to be blank.
This is my server.js file
'use strict';
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
router = require('./api'),
bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/my_db');
app.use(bodyParser.json());
app.use('/api', router);
app.get('/', function(req, res) {
res.render(__dirname + '/index.jade');
});
app.listen(3001, function() {
console.log('Listening on port 3001');
});
and this is my api/index.js file:
'use strict';
var express = require('express'),
Todo = require('../models/todo'),
router = express.Router();
router.get('/todos', function(req, res) {
Todo.find({}, function(err, todos) {
if(err) {
return console.log(err);
}
res.json({todos: todos});
});
});
router.post('/todos', function(req, res) {
var todo = req.body;
res.json({todo: todo});
});
module.exports = router;
when I use postman to post this to http://localhost:3001/api/todos:
{
'name': 'Walk the Dog',
'completed': false
}
my response is:
{
"todo": {}
}
I can't see why this would be blank, any help is appreciated.
UPDATE
Turns out I was posting text in postman instead of JSON.
use this in your server.js file
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

Categories

Resources