When I visit mysite.com/verify/myusn the result is a 404 error. When I visit mysite.com/ it serves me the index page as expected.
When I turned on the debugger, I realized Express was trying to serve a static file instead. But it also shows my route being registered properly. Please help me out.
Here is my debugger:
Here is my server.js:
var express = require('express');
var app = express();
var path = require('path');
app.get('/*', function(req, res, next){
next();
});
app.use(express.static(path.join(__dirname , '/_site/') , {maxAge:0}));
app.use('/assets/', express.static(path.join(__dirname , '/_site/assets') , {maxAge:0}));
var routesLogin = require(path.join(__dirname, '/api/routes/users'));
routesLogin(app);
app.get('/', function(req, res) {
res.sendFile( path.join(__dirname , '/_site/landing.html'));
});
app.get('*', function(req, res) {
res.send('404');
});
app.post('*', function(req, res) {
res.send('404');
});
port = process.env.PORT || 3000;
app.listen(port);
console.log('listening on ' + port);
./api/routes/users.js:
module.exports = function(app){
var users = require('../controllers/userController');
app.route('verify/:usn')
.get(users.verifyUSN)
};
./api/controllers/userController.js:
exports.verifyUSN = function(req, res, next){
res.status(200)
.json({
status: 'success',
data: data,
message: 'USN Verified.'
});
}
I believe your problem could potentially be in /api/routes/users.js
module.exports = function(app){
var users = require('../controllers/userController');
// previously app.route('verify/:usn')
app.route('/verify/:usn')
.get(users.verifyUSN)
};
Hope this helps.
Related
I am building a day planner, and while I was setting the routes I noticed I am receiving a 404 for every routes other than the main Home page route ie, index or "/".
This is app.js file
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var calendarRouter = require('./routes/calendar');
var app = express();
//Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb+srv://<user-name>:<password>#cluster0.3xw67.gcp.mongodb.net/<db-name>?retryWrites=true&w=majority';
mongoose.connect(mongoDB, { useNewUrlParser: true , useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/calendar', calendarRouter);
// 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;
This is the calendar.js route
var express = require('express');
var router = express.Router();
var schedule_controller = require('../controllers/scheduleController');
router.get('/', schedule_controller.index);
router.get('/calendar/create', schedule_controller.schedule_create_get);
router.post('/calendar/create', schedule_controller.schedule_create_post);
router.get('/calendar/:id/delete', schedule_controller.schedule_delete_get);
router.post('/calendar/:id/delete', schedule_controller.schedule_delete_post);
router.get('/calendar/:id/update', schedule_controller.schedule_update_get);
router.post('/calendar/:id/update', schedule_controller.schedule_update_post);
router.get('/calendar/event/:id', schedule_controller.schedule_details);
router.get('/events', schedule_controller.schedule_list);
module.exports = router;
This is the index.js route, I did a redirect here!
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.redirect('/calendar');
});
module.exports = router;
And here is the Controller for the calendar.js route.
var Schedule = require('../models/schedule');
exports.index = function(req, res) {
res.send('NOT IMPLEMENTED: Site Home Page');
};
exports.schedule_list = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule List');
};
exports.schedule_details = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule Detail: ' + req.params.id);
};
exports.schedule_create_get = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule create GET');
};
exports.schedule_create_post = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule create POST');
};
exports.schedule_delete_get = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule delete GET');
};
exports.schedule_delete_post = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule delete POST');
};
exports.schedule_update_get = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule update GET');
};
exports.schedule_update_post = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule update POST');
};
Okay I found the bug it was me using index url that is / which I redirected to /calendar. And I have been using the rest of the url routes without calling the redirected one ie, /calendar.
I tried calling the routes with /calendar/calendar and it works!
I don't yet know clearly how to explain this. I hope fellow stackoverflow'ers could explain why this is happening.
Here's me trying a noob explanation!
Redirecting index route / to another url route, changes the main url route of the website(address). So all the sub routes which is everything other than the index route should explicitly call the redirected route (new address). Because every-time we call the old address the redirection changes it to the new one. Making the old address a dead one.
(Humour : I would like to point out an example considering numbers. It's like whole numbers and natural numbers. Redirection is when the whole number changes to natural number.)
so I am experimenting with it locally, this is in my hosts file
127.0.0.1 example.dev
127.0.0.1 www.example.dev
127.0.0.1 api.example.dev
and this is my code:
var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
var router = express.Router();
// example.com
app.get('/', function(req, res) {
res.send('Homepage');
});
//api specific routes
router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
router.get('/users', function(req, res) {
res.json([
{ name: "Brian" }
]);
});
app.use(subdomain('api', router));
app.listen(3000);
it's basically the example from the package website
api.example.dev/users works well, but when I go to to api.example.dev the content is the same as on example.dev (like it is overwritten)
any ideas what I am doing wrong?
thanks
This is a order of requests processing problem. Move the declaration of the request handler for the main domain after the subdomain:
var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
var router = express.Router();
//api specific routes
router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
router.get('/users', function(req, res) {
res.json([
{ name: "Brian" }
]);
});
app.use(subdomain('api', router));
// example.com
app.get('/', function(req, res) {
res.send('Homepage');
});
app.listen(3000);
learn express and faced with problem. After i create module body-parser begin don't work. All requests are complited, but data don't parsing.
let express = require('express');
let bp = require('body-parser');
let dishRouter = require('./dishRouter');
let app = express();
let hostname = 'localhost';
let port = 8080;
dishRouter.use(bp.json()); //don't work
app.use('/dishes', dishRouter);
app.use(express.static(__dirname + '/public'));
app.listen(port, hostname, function(){
console.log(__dirname);
console.log(`Server has running at http://${hostname}:${port}`);
});
//My dishRouter module
let express = require('express');
let router = express.Router();
router.route('/')
.all(function(req, res, next){
res.writeHead(200, {'Content-type': 'text/plain'});
next();
})
.get(function(req, res, next){
res.end('We will dish for you');
})
.post(function(req, res, next){
res.end('Will add the dish:' + req.body.name + ' with details: ' + req.body.description);
})
.delete(function(req, res, next){
res.end('Deleting all dishes');
});
module.exports = router;
As this Example you miss send after rest:
app.route('/book')
.get(function(req, res) {
res.send('Get a random book');
})
.post(function(req, res) {
res.send('Add a book');
})
.put(function(req, res) {
res.send('Update the book');
});
i can't access to my express application's home page by '/' route pattern. it's working on /index e.g. My express version is 4.6.
I tried app.use('/*', router), but my application is not responding or 503 service temporarily unavailable. It's now working by '/index' pattern and other routes is working correctly. only '/' pattern is not working. :)
Here is my code snippet.
var http = require('http');
var express = require('express');
var app = express();
var router = express.Router();
app.use('/', router);
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('./public'));
var bodyParser = require("body-parser");
app.use(bodyParser());
var fs = require('fs');
var clientSessions = require("client-sessions");
var form = require('express-form');
var field = form.field;
var sha1 = require('sha1');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: process.env.OPENSHIFT_MYSQL_DB_HOST,
port: process.env.OPENSHIFT_MYSQL_DB_PORT,
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database: process.env.OPENSHIFT_GEAR_NAME
});
var multer = require('multer');
var done = false;
app.use(clientSessions({
secret: 'xxxxx'
}));
app.use(function(req, res) {
res.status(400);
res.render('pages/404');
});
// Handle 500
app.use(function(error, req, res, next) {
res.status(500);
res.render('pages/500');
});
//---
app.use(multer({
dest: 'public/uploads/',
rename: function(fieldname, filename) {
return filename + Date.now();
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function(file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
done = true;
}
}));
//// --------------- start app routes --------------//
// ----- GET -----
router.get('/', function() { // THIS PATTERN IS NOT WORKING
console.log('hello world'); // this line is not working
connection.query(strQuery, function(err, rows) {
// res.render('pages/index');
});
});
Because you didn't handle "/", here is updated code
var router = express.Router();
app.use('/*', router);
router.get('/', function(req, res) {
res.send('welcome home');
}
router.get('/index', function(req, res) {
res.send('welcome index');
}
You are forgetting '*' in second line
app.use('/*', router);
Do you forget to make redirection?
router.get("/", function (req, res) {
res.redirect("/index");
});
I'm using the code below to learn a bit about the new express.js (4.0). I can't seem to understand why the logging is happening regardless of which path I hit with my browser. Shouldn't it only log for website.get and not for api.get paths?
// Express 4.0 test...
var express = require('express');
var app = express();
var website = express.Router();
var api = express.Router();
var port = process.env.PORT || 3000;
website.use(function (req, res, next) {
console.log(req.method, req.url);
next();
});
website.get('/', function (req, res) {
res.send('Home page');
});
website.get('/about', function (req, res) {
res.send('About page');
});
api.get('/', function (req, res) {
res.send({'json':'response'});
});
api.get('/user', function (req, res) {
res.send({'user':'john'});
});
// app.get('/', function (request, response) {
// response.writeHead(200, {"Content-Type": "text/html"});
// response.end("<h1>Hello, World!</h1>");
// });
app.use('/', website);
app.use('/api', api);
app.listen(port);
console.log('http(s) server revved up on port ' + port);
Any help would rock!
Update: I see, because '/api' matches '/', website gets applied to all routes. Is there any way to avoid this?
probably define the /api router first and the other one - second.
app.use('/api', api);
app.use('/', website);