AJAX POST请求服务器无法正常工作

时间:2016-01-17 19:35:58

标签: javascript ajax node.js post

我正在使用node.js构建应用程序,我有以下POST请求:

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);
        }
    });

服务器端API:

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

问题是服务器没有收到POST请求。我通过服务器端的控制台记录文本进行检查,但它没有返回任何内容......

任何人都知道可能会发生什么?

提前致谢!

1 个答案:

答案 0 :(得分:0)

也许问题是ajax调用。尝试通过执行此脚本来测试服务器:

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"} );

希望它可以帮助你弄清楚出了什么问题。

相关问题