在AJAX调用路由后节点重定向,而不是仅返回数据

时间:2016-05-08 17:11:27

标签: javascript ajax node.js express

我正在尝试向我的一条路线发出AJAX请求,这些路由应返回一些数据,但我无法解决这样一个事实:当我发出一个AJAX请求时,我被重定向到我要求的路由。

如何防止这种情况发生?

我要求的路线:

app.post('/signin', function(req, res) {
    request.post({
        url:'http://localhost:3000/api/authenticate',
        form: {
            email: req.body.email,
            hashed_password: req.body.password
        },
    }, function(err, httpResponse, body) {
        console.log(req.xhr);
        console.log(req.headers);
        if (err) {
            return console.error('failed:', err);
        }
        console.log('successful! ', JSON.parse(body));
        //user.token = data.token;
        res.json(JSON.parse(body));
    });
});

我的AJAX请求:

    var request    = new XMLHttpRequest();
    var url        = 'http://localhost:3000/signin';

    var credentials = {
        email: document.getElementsByName('email')[0].value,
        password: document.getElementsByName('password')[0].value
    };

    JSON.stringify(credentials);

    request.onreadystatechange = function() {
        if (request.readyState == XMLHttpRequest.DONE) {
            if(request.status == 200) {
                if(request.readyState == 4) {
                    var data = JSON.parse(request.responseText);
                    console.log(data);
                }
            } else if(request.status == 400) {
                console.log('There was an error 400');
            } else {
                console.log('something else other than 200 was returned');
            }
        }
    }

    request.open('POST', url, true);
    request.setRequestHeader('Accept', 'application/json');
    request.setRequestHeader('Content-Type', 'application/json');
    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    request.send(credentials);

0 个答案:

没有答案