I am working on a university/student project with full MEAN stack. We have NodeJS, ExpressJS backend and Angular2 frontend. Backend runs on localhost:8080
and frontend runs on localhost:4200
This is how my backend looks like
var express = require('express'),
...
var app = express();
...
// needed because of cross origin resource sharing during development
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var port = process.env.PORT || 8080;
var loginController = require('./controllers/loginController')(Person);
var personController = require('./controllers/personController')(Person, Transaction);
var transactionController = require('./controllers/transactionController')(Person, Transaction);
var apiRouter = express.Router();
apiRouter.post('/login', loginController.authenticate);
/**
* Middleware that handles authorization of particular routes.
* Every request which starts with `/api/persons` or `/api/transactions`, will be intercepted and validated against JWT.
*/
apiRouter.use(function (req, res, next) {
// JWT gets validated
});
apiRouter.get('/persons', personController.fetchAllPersons);
apiRouter.get('/persons/:personId', personController.fetchPersonById);
apiRouter.get('/persons/:personId/transactions', personController.fetchTransactionsByPersonId);
apiRouter.post('/transactions', transactionController.addNewTransaction);
app.use('/api', apiRouter);
app.listen(port, function () {
console.log('Listening on port: ' + port);
});
I read that the routes of the express router get executed sequentially, so the order of middleware inclusion is important. Therefore I set it after /login
route since it should not be available without JWT authorization. When I start the application and execute requests with postman
everything works as it is supposed, but when I try to login from the frontend middleware function gets executed also for login route but it shouldn't, right?
Is is maybe because of they are running on different ports or could it be an issue caused by cross origin, I really have no idea? Did anyone already face similar issue and could you please explain this behavior? Thx
via amsalk
No comments:
Post a Comment