I really don't understand why node(express) just render index page and return 404 for other pages ("comproAffitto" in the example).
app.js
var index = require('./routes/index');
var comproAffitto= require ('./routes/comproAffitto');
...
...
app.use('/', index);
app.use('/comproAffitto', comproAffitto);
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/comproAffitto.js
var express = require('express');
var router = express.Router();
/* GET comproAffitto page. */
router.get('/comproAffitto', function(req, res, next) {
console.log("dentro");
res.render('comproAffitto', { title: 'Exprrress' });
});
module.exports = router;
html href
<a href="/comproAffitto/" class ....
console log
GET /comproAffitto/ 404
where is the problem?
thank you all
You are constructing the path two times: /comproAffitto/comproAffitto.
You should remove one of them or here:
app.use('/', comproAffitto);
or there:
routes/comproAffitto.js
var express = require('express');
var router = express.Router();
/* GET comproAffitto page. */
router.get('/', function(req, res, next) {
console.log("dentro");
res.render('comproAffitto', { title: 'Exprrress' });
});
module.exports = router;
leaving app.use('/comproAffitto', comproAffitto);
You defined /comproAffitto/comproAffitto instead of /comproAffitto
You would need to either change this:
app.use('/comproAffitto', comproAffitto);
to this:
app.use('/', comproAffitto);
or this:
router.get('/comproAffitto', function(req, res, next) {
to this:
router.get('/', function(req, res, next) {
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.)
I have the following snippet of code and when I access the local host I get an error: Cannot GET /
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.send("function has started");
});
express().listen(3001);
module.exports = router;
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('GET request to the homepage')
})
app.listen(3001)
This should be fine
If you want to use the router, you need to use the use method example (app.use('/', router):
var express = require('express');
var router = express.Router();
var app = express()
/* GET home page. */
router.get('/', function (req, res, next) {
res.send("function has started");
});
app.use('/', router)
app.listen(3001);
I am trying to the replicate an example, just change ng-model name, and the url to communicate the client with the server, but that error show up.
Error
POST https://nuevohorario.herokuapp.com/enviarAsignatura 404 (Not Found)
Possibly unhandled rejection: {"data":"<h1>Not Found</h1>\n<h2></h2>\n<pre></pre>\n","status":404,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/enviarAsignatura","data":{"data":"calculo"},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"Not Found"}
Client -> Front - End
.controller('ctrl-asignatura',function($scope,sk,$http){
$scope.date= new Date();
$scope.data=[];
var vector = [];
$scope.m=function(){
$http.post('/enviar', {data : $scope.asignatura}).then(function(response){
console.log(response);
})
}
sk.on('registrar',function(s){
alert(s);
});
Back End -> Node Js - Socket.IO
var express = require('express');
var router = express.Router();
var misocket = require('../routes/misocket');
/* GET users listing. */
router.post('/enviar', function(req, res, next) {
console.log(misocket);
misocket.emit("registrar",req.body);
console.log(req.body);
res.status(200).json({
message : "send message"
});
});
module.exports = router;
misocket.js
var i =0;
var ioapp;
exports.connection= function(io){
ioapp=io;
io.on('connect',function(s){
console.log("conetado");
})
}
exports.io=ioapp;
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;
It seems you are useing Router-level middleware
var router = express.Router()
Try to load router-level middleware by using the router.use() functions.
router.use('/enviarAsignatura', function(req, res, next) {
//your code here
}
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);
In the code below I want to restrict access to the 'restrictedRoutes' routes without authorization. But in this case 'restrictedRoutes' affects on any routes excluding 'router'.
For example, if I try to access to the '/test', I want to get 404 error, but instead I'm getting JWT-error about invalid token, If that not provided.
How I can create middleware, that will affects only on routes that provided by certain 'Router'?
/*
* API Routes file
*/
var jwt = require('jsonwebtoken');
var router = require('express').Router();
var restrictedRouter = require('express').Router();
module.exports = function (express, app) {
//Default routes
router.get('/login', app.controllers.HomeController.login);
restrictedRouter.use(function (req, res, next) {
try {
var tokenArray = req.headers.authorization.split(' ', 2);
if (jwt.verify(tokenArray[1], 'shh'))
next();
} catch (exception) {
res.status(401).json({error: exception.message});
}
});
//Restricted routes
restrictedRouter.get('/', function (req, res) {
res.send('Success');
});
express.use(router);
express.use(restrictedRouter);
};
Mount the router to some path you want to be restricted.
app.use('/restricted', restrictedRouter);
Also I'd avoid the confusion of passing along express and app like you are doing and instead do it like this:
index.js
var express = require('express');
var app = express();
var routes = require('./routes');
app.use('/restricted', routes.restrictedRouter);
app.use(routes.router);
routes.js
var express = require('express');
exports.router = express.Router();
exports.restrictedRouter = express.Router();
router.get('/login', app.controllers.HomeController.login);
restrictedRouter.use(function (req, res, next) {
try {
var tokenArray = req.headers.authorization.split(' ', 2);
if (jwt.verify(tokenArray[1], 'shh'))
next();
} catch (exception) {
res.status(401).json({error: exception.message});
}
});
//Restricted routes
restrictedRouter.get('/', function (req, res) {
res.send('Success');
});
Your other option is to use the middleware per route:
var authMiddleware = function (req, res, next) {
try {
var tokenArray = req.headers.authorization.split(' ', 2);
if (jwt.verify(tokenArray[1], 'shh'))
next();
} catch (exception) {
res.status(401).json({error: exception.message});
}
});
router.get('/', authMiddleware, function(req, res) {
res.send('Success');
});