简体   繁体   中英

building a NodeJs Express Router structure with Ajax POST

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:

  • the route itself
  • the Ajax call "validateLogin"

.

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

http://expressjs.com/en/guide/routing.html

假设所有其他设置都正确设置,根据代码的设置,您似乎要访问的url实际上位于/login/validateLogin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM