首页 > 解决方案 > 使用 NodeJS 的 Ajax 请求处于挂起状态

问题描述

我正在尝试通过单击按钮进行 ajax 调用...但是调用没有到达节点层。HTML 标记:显示最新的手机

应用程序.js:

function postDetails() {
    $.post('/api/users', {data: 'blah'}, function (data) {
        console.log(data);
      });
}

服务器.js

http.createServer(function(req, res) {
    if(req.url == '/') {
        fs.readFile("index.html", function(err, html) {
        res.end(html);
    });
    } else if(req.url.match("\.css$")) {
        var cssPath = path.join(__dirname, 'public', req.url);
        var fileStream = fs.createReadStream(cssPath, 'UTF-8');
        res.writeHead(200, {"Content-Type" : "text/css"});
        fileStream.pipe(res);
    } else if(req.url.match("\.js$")) {
        var cssPath = path.join(__dirname, 'public', req.url);
        var fileStream = fs.createReadStream(cssPath, 'UTF-8');
        res.writeHead(200, {"Content-Type" : "text/javascript"});
        fileStream.pipe(res);
    }

}).listen(8000);


app.post('/api/users', function(req, res) {
    console.log('KKKKKKKKKKuuuuuuuuuuuuuuKKKKKKK');
    router.post('/', function (req, res) {
      res.set('Content-Type', 'application/json');
      var jsonData = JSON.stringify(req.body);
      res.status(201);
      res.json();
    });
});

标签: node.jsajaxexpress

解决方案


我认为这是因为您正在使用http创建服务器和侦听请求,并尝试使用app处理路由(假设 Express 对象)。

所以要么你应该在http.createServer 的回调函数中编写路由代码,就像这样 -

http.createServer(function(req, res){
  if(req.url == '/api/users' req.method === 'POST'){
    //your code here
  }
});

或者您应该使用app(快速方式)创建服务器


推荐阅读