Reputation: 1580
I want to use the Express router for my project. I create my app.js
(my view engine is Handlebars)
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
require('./server/router')(app); // start with the routing
app.listen(8888);
and head over to my router.js
where I handle all the route files
module.exports = function(app){
var router = require('express').Router();
app.use('/login', require('./routes/login'));
app.use('/route2', require('./routes/route2'));
app.use('/route3', require('./routes/route3'));
router.post('/logout', function (req, res) {
var session = req.session;
session.destroy();
res.send({});
});
};
My login route deals with two tasks:
.
var router = require('express').Router(); // I set this on each route
router.get('/', function (req, res) { // render the HTML template
res.render('login');
});
router.post('/validateLogin', function (req, res) { // user login - AJAX
var loginIsValid = true; // TEST // req.body.username && req.body.password
res.send({
isValid: loginIsValid
});
});
module.exports = router; // export this module
The client has a simple login form. When pressing the login button I execute this Ajax call
function login() {
$.ajax({
type: 'POST',
url: 'validateLogin',
contentType: 'application/json',
data: JSON.stringify({
username: "Foo",
password: "Bar"
})
}).done(function (response) {
if (response.isValid) { // Redirect the user to the next page
$(location).attr('href', 'next page');
}
}).fail(function () {
});
}
This Ajax call fails because the POST route can't be found
POST http://localhost:8888/validateLogin 404 (Not Found)
Even using
url: '/validateLogin',
does not work.
What is missing or wrong? Is my structure fine?
I took the information from
Upvotes: 0
Views: 974
Reputation: 3863
Assuming all else is setup correctly, based on your code's setup it seems the url you want to access is actually located at /login/validateLogin
Upvotes: 1