I'm using NODE.js and Express (express-generator) to create a website. I had this working just fine yesterday afternoon, but I guess I changed something and it doesn't work now. My firewall is turned off.
I get the following in my console.
C:\website>node bin/www
Listening on 8080
Get / - - ms - -
Get / - - ms - -
Get / - - ms - -
Each of those Get / - - ms - - happens each time I try to go to 127.0.0.1:8080
Here is my bin/www file:
#!/usr/bin/env node
var debug = require('debug')('test');
var app = require('../app');
app.set('port', process.env.PORT || 8080);
var server = app.listen(app.get('port'), function() {
console.log("Listening on " + server.address().port);
debug('Express server listening on port ' + server.address().port);
});
And my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
// production error handler
app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log(err);
});
module.exports = app;
This behavior might be the result of incorrectly defined routes. Your routes should follow this pattern:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Related
I am writing nodejs express to fetch the data to web page. an error appear 404 Not Found when open
http://127.0.0.1:3000/users
in the Dev tool on the browser show: users:1 GET http://127.0.0.1:3000/users 404 (Not Found)
below are the app.js and index.js and users.js files
I think I have an issue with the routes
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');
var mysql = require('mssql');
// var connection = require('./lib/db');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
//I put false instead true
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: '123456cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))
app.use(flash());
app.use(expressValidator());
app.use('/', indexRouter);
app.use('/list', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
below are the routes files.
routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
routes/users.js
var express = require('express');
var router = express.Router();
var connection = require('../database.js');
/* GET home page. */
router.get('/', function(req, res, next) {
connection.query('SELECT * FROM users',function(err,rows) {
if(err){
req.flash('error', err);
res.render('list',{page_title:"Users - Node.js",data:''});
}else{
res.render('list',{page_title:"Users - Node.js",data:rows});
}
});
});
module.exports = router;
As I already mentioned in my comment, you don't have a /user route therefore you will get a 404 NotFound error.
Change this
app.use('/list', usersRouter);
To this
app.use('/user', usersRouter);
Every time I call: http://localhost:3000/api/tasks am getting a Cannot GET /api/tasks
My server.js
var express = require('express');
var path = require('path');
var BodyParser = require('body-parser');
var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 3000;
var app = express();
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// Set Static Folder
app.use(express.static(path.join(__dirname, 'client')));
// Body Parser MW
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('api', tasks);
app.listen(port, function(){
console.log('Server started on port '+port);
});
I am still learning the ropes. Thank you in advance
tasks.js
var express = require('express');
var app= express();
var mongojs = require('mongojs')
var db = mongojs('mongodb://<user>.:<****>#ds125365.mlab.com:25365/mytasklist_wafalme', ['tasks'])
// Get All Tasks
app.get('/tasks', function(req, res, next){
db.tasks.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
// Get Single Tasks
app.get('/tasks/:id', function(req, res, next){
db.tasks.findOne({_id: mangojs.ObjectId(req.params.id)}, function(err, task){
if(err){
res.send(err);
}
res.json(task);
});
});
module.exports = app;
I have attached the task.js file that runs in the routes folder with the index.js
Use an absolute route to define the API routing context:
app.use('/', index);
app.use('/api', tasks);
Always include a forward slash (/) at the beginning of your routes.
I'm trying to build a server that user will be able to enter these valid paths:
localhost:9090/admin
localhost:9090/project1
and in case the user enters anything else invalid such as these the user will be redirected to root and then to the default path localhost:9090/404.html:
How do I do it?
this is my code:
app.js
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})
route.js
'use strict';
var express = require('express');
var app = express();
var router = express.Router();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index');
});
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
res.render('c:/monex/myprojects/' + name +'/index');
});
app.use(function(req, res, next){
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
});
module.exports = router;
Expressjs has a pretty cool way of handling errors and routing them.
1/ To Confirm if project exists
We use the filesystem module to confirm if it exists, using the access API, you can read more on the module at https://nodejs.org/dist/latest-v6.x/docs/api/fs.html
var fs = require('fs') // We'll need to ask the filesystem if it exists
var projectname = 'myfolder';
// Excerpt from your code, but Modified
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
fs.access(name, fs.constants.F_OK, function(err) {
if(!err) { // directory exists
res.render('c:/monex/myprojects/' + name + '/index');
return;
}
// Directory does not exist
next({statusCode: 404});
})
});
2/ To route the error properly
From the above code, we said anytime directory does not exist in nodejs, call next with an error object, i.e next(err), the difference between next() and next(err) is that there are two types of middlewares in expressjs, the first is:
app.use("/", function(req, res, next) {})
while the second is
app.use("/", function(err, req, res, next) {})
The difference between the two is that, the first one is a normal middleware that routes requests through. But the second is called a error handling middleware. Anytime that next function is called with an argument, express jumps to route it through error handling middlewares from there on. So, to solve your problem.
You will want to solve this at the app level so that all across all routers, you can have 404 pages delivered.
In app.js
function Error404(err, req, res, next) {
if(err.statusCode === "404") {
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
}
// YOu can setup other handlers
if(err.statusCode === "504") {}
}
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(Error404);
REFERENCES
http://expressjs.com/en/guide/error-handling.html
https://www.safaribooksonline.com/blog/2014/03/12/error-handling-express-js-applications/
https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
Try changing the signature of your 404 handler function
Express will use it as an error handler of just add change function parameters to: (err, req, res, next)
I also got it fixed by adding this to my app.js
app.use(function (err, req, res, next) {
res.render('c:/monex/505.html', { status: 500, url: req.url });
})
making it look like this
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(function (err, req, res, next) {
res.render('c:/monex/404.html', { status: 404, url: req.url });
})
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})
I cannot access any request parameters. e.g. req.body.username. for some reason req.body is always undefined. The endpoint is /youtube
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
server.js
var express = require("express");
var mysql = require('mysql');
var app = express();
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
user : 'user',
password : 'pass',
database : 'db',
debug : false
});
var router = express.Router();// get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Incoming request');
next(); // make sure we go to the next routes and don't stop here
});
app.get("/",function(req,res){-
handle_database(req,res);
});
router.route('/youtube')
.post(function(req, res) {
console.log(req.body); // always undefined
})
.get(function(req, res) {
});
app.use('/api', router);
app.listen(3000);
console.log("Listening on port 3000....")
Add those 3 lines right below var app = express(); in server.js:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Now your req.body will not be undefined.
I have a Experss.js framework and Node.js with a request to MS SQL database on the server side.
I want to get a data(in JSON or array) from server and send to Cliend side.
I don't understand how can I write routers for another server on the Client side.
server.js
npm start
http://localhost:5000/
Code:
var sql = require("mssql");
var express = require('express');
var app = express();
var http = require('http')
var query = "SELECT AVG([sta_waittime]) AS Spalte FROM [DialogMaster_TEST].[dwh].[anruf_stat] WHERE CONVERT(DATE,sta_timestamp) = CONVERT(DATE,CONVERT(DATE,'2016-08-01')) ";
app.get('/', function (req, res) {
sql.connect("mssql://log:pas#db/TEST").then(function() {
// Query
new sql.Request().query(query).then(function(recordset) {
var a = [];
a.push(recordset[0].Spalte);
res.send(a); // **number**
}).catch(function(err) {
// ... query error checks
});
}).catch(function(err) {
// ... connect error checks
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Server site in Browser:
My app.js file.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
//app.get('/');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
You need only 1 server(REST server). Just use node.js server.
Read it:
REST