Nodejs CANNOT GET - node.js

I've been trying to do a route in Express. For example one /about route, but it doesn't work.
var express = require('express');
var app = express();
var router = express.Router();
var moment = require('moment');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/', function (req, res) {
//some action
});
app.get('/time', function (req, res) {
//...
});
app.get('/about', function (req, res) {
res.send('about');
});
Currently after calling url/about I'm getting Cannot GET /about as a return and after some research I've got no idea how to resolve this issue. They even describe it that way in the official express docs.
Thank you in advance.

You have something like this in your code? :
app.listen(SERVER_PORT, function () {
console.log("Server successfully started on port:" + SERVER_PORT); });

We should have something like this:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
const app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/about', routes.about);
and also in the views folder: about.jade

Related

Express nodejs POST method return empty brackets

I can't get the value in my form. I am using a basic HTML form to send my data. When I try to test the return of the POST method in the console, I can't find the value of my input. This is my code:
let express = require('express');
let app = express();
// Moteur de template
app.set('view engine', 'ejs');
// Middleware
app.use('/assets', express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Routes
app.get('/', (request, response) => {
response.render('pages/index');
});
app.post('/', (req, res, next) => {
console.log(req.body);
});
app.listen(8080);
my console always return {}
Add this to the front of your code:
app.use(express.urlencoded({ extended : true}));
app.use(express.json());
body-parser is no longer needed, as this feature is already provided in express.js.
also I would suggest you to do const express = require('express'); const app = express(); instead of let express = require('express'); let app = express();.
Do npm install 'body-parser
Then update your code like this
let express = require('express');
let app = express();
// For FORM input
var bodyParser = require('body-parser');
// Moteur de template
app.set('view engine', 'ejs');
// Middleware
app.use('/assets', express.static('public'));
// Body parser For forms Actions
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// Routes
app.get('/', (request, response) => {
response.render('pages/index');
});
app.post('/', (req, res, next) => {
console.log(req.body);
});
app.listen(8080);
This should fix it

res.Send it results in 404 error?

Hi I am trying display the message : respond with a resource from routes folder/user.js
exports.list = function (req, res) {
res.send("respond with a resource");
};
But I am getting an error 404 in command prompt.And in url
localhost:8080\user where the response is sent I get the message:
Cannot GET /user
my app.js has code:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
The example I am working on is from https://www.youtube.com/watch?v=czmulJ9NBP0. and time is at 1.37.41
Your route is named /users not /user. So try navigating to /users in your browser instead and it should work.

How to get post params in app.post

I am developing nodejs project. Where I am using ejs with the help of express-helpers module to generate view template html.
in server.js file I have written below code
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var app = express();
var helpers = require('express-helpers')
helpers(app);
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// respond with "index.html" when a GET request is made to the homepage
app.get('/', function(req, res) {
res.render('index.html');
});
app.get('/demo', function (req, res) {
res.render('demo.ejs');
});
app.post('/demo', function (req, res) {
console.log(res.body)
});
I want to know that in app.post how should id get post params
app.post('/demo', function (req, res) {
console.log(res.body)
});
I have tried console.log(req.body) but giving as undefined
Also tried console.log(res.body) but giving as undefined
Let me know how should I implement it?
you should use a middleware such as body-parser
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/demo', function (req, res) {
console.log(req.body)
});
Use the body-parser middleware. First, you need to install it using npm install body-parser. And then use it in your application like this
var bodyParser = require('body-parser');
.....
// For Content-Type application/json
app.use(bodyParser.json());
// For x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
....
app.post('/demo', function (req, res) {
console.log(req.body);
});

How to move route function to another js file in express.js?

I have the following code (app.js):
var express = require('express');
var bodyParser = require('body-parser');
var mongoskin = require('mongoskin');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var db = mongoskin.db('mongodb://#localhost:27017/testdb', {safe:true})
app.param('orders', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.use('/', routes);
app.get('/api/:orders', function(req, res, next) {
req.collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
Which works. What I'm going to do is to move the route (/api/:order) to another js file (routes/api.js). Here is the code:
var express = require('express');
var bodyParser = require('body-parser');
var mongoskin = require('mongoskin');
var routes = require('./routes/index');
var api = require('./routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var db = mongoskin.db('mongodb://#localhost:27017/testdb', {safe:true})
app.param('orders', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.use('/', routes);
app.use('/api', api);
The /routes/api.js file:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('respond with a resource');
});
// return all orders
router.get('/:orders', function(req, res, next) {
req.collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
module.exports = router;
I got the following error:
TypeError: Cannot call method 'find' of undefined
Can anybody tell me what's wrong with my code? Thanks.
I assume req.collection is undefined, because app.param('orders') is not executed for the other router.

Using piler with express 3 and nodejs

I want to run Express 3.3.x with its default implementation.
Express uses its routes module, so what I have to do, if JS and CSS is accessible by any view in any route?
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var piler = require('piler');
var mongoose = require('mongoose');
var config = require('./config');
var app = exports.app = express();
var js = piler.createJSManager();
var css = piler.createCSSManager();
var srv = require('http').createServer(app);
// all environments
js.bind(app,srv);
css.bind(app,srv);
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
js.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
/**
* Routes
*/
var routes = require('./routes');
app.get('/', routes.index);
srv.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
In the example of piler:
app.get("/", function(req, res){
res.render("index.jade", {
layout: false,
js: js.renderTags(),
css: css.renderTags()
});
});
This works. But I have
app.get('/', routes.index);
So what I have to do, that js.renderTags() works in every view?
If you are trying to pass variables to render, you can use res.locals
app.use(function(req,res,next){
res.locals.layout= false;
res.locals.js= js.renderTags();
res.locals.css= css.renderTags();
next();
});
Use this before your router but don't overwrite your locals (res.locals={...})

Resources