简体   繁体   中英

AJAX POST request to server not working

I am building an app using node.js and I have the following POST request:

var api = express.Router();

$.ajax({
        type: "POST",
        url: "/api/login/",
        data: context,
        success: function(data, status) {
            console.log('succeeded!!');
        },
        error: function(data, status, res) {
            console.log('error :(');
            console.log(res);
        }
    });

Server side API:

api.post('/api/login/', function(req, res) {
    console.log('login api hit'); //does not console log
});

The problem is the server does not receive the POST request. I checked by console logging text on the server side, but it does not return anything...

Anyone know what might be going on?

Thanks in advance!

Maybe the problem is the ajax call. Try to test the server by executing this script:

var http = require('http');

var options = {
  host: '127.0.0.1',
  port: 8080,
  // if it's not localhost, put 'hostname' instead host and port
  //hostname: 'some_url.net',
  path: '/api/login/',
  method: 'POST',
  dataType: 'json'
};

function sendRequest( data ) {
    var req = http.request( options, function( res ) {
        console.log( 'STATUS: ' + res.statusCode );
        //console.log( 'HEADERS: ' + JSON.stringify(res.headers) );
        res.setEncoding( 'utf8' );
        res.on( 'data', function( chunk ) {
            console.log( 'BODY: ' + chunk );
        });
        req.on('error', function( e ) {
            console.log( 'problem with request: ' + e.message );
        });
    });
    // write data to request body
    req.write( JSON.stringify(data) );
    req.end();
}

sendRequest( {"some":"data"} );

Hope it helps you to figure out what is going wrong.

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