使用 jQuery 从 NodeJS 服务器请求数据

Request data using jQuery from a NodeJS server

本文关键字:请求 数据 服务器 NodeJS jQuery 使用      更新时间:2023-09-26

我有以下客户端代码(在浏览器或atom-shell/node-webkit Web API中运行(:

$(document).ready(function(){
    $.ajax({
        url: 'http://127.0.0.1:1337/users',
        type: 'GET',
        dataType: 'json',
        success: function(res)
        {
            console.log(res);
        }
    });
});

非常简单的东西,它从服务器请求JSON格式的用户列表。

现在在服务器端(节点 API(上,我有以下代码:

var http = require('http');
var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : '127.0.0.1',
  user     : 'admin',
  password : 'qwe123'
});
// Create the server
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('This is just a placeholder for the index of the server.');
}).listen(1337, '127.0.0.1');    
// Build a response
http.get('http://127.0.0.1:1337/users', function(res) {
  var json = { 'status' : res.statusCode, 'response' : res };
  JSON.parse(json);
}).on('error', function(e) {
  var json = { 'status' : e.statusCode, 'message' : e.message };
  JSON.parse(json);
});

我对如何创建服务器然后有效地创建可以通过客户端代码与之通信的端点(例如/users(感到困惑。

1.( 我认为http.get只从已经建立的端点获取数据是否正确?那createSever实际创建端点?还是在创建服务器后有另一种创建这些端点的速记方法?所以基本上在这个例子中不需要 get 请求,因为我想在客户端请求它。

2.( 无论如何,我需要创建此端点/users并返回以下内容:

connection.connect();
connection.query('SELECT * FROM users', function(err, results) {
    JSON.parse(results);
});
connection.end();

谁能帮我指出正确的方向?似乎我错过了文档中可以在服务器上创建不同端点的部分。

恐怕你混合了expressjs和node http模块。如果你只是使用节点"http",请参考这个:Nodejs提供1个api端点和一个html页面,关于如何实现URL的路由。

综上所述,我建议您查看库 expressjs 为此:http://expressjs.com/starter/basic-routing.html。它在很大程度上简化了路由管理并提供了更多功能。

希望这对你有帮助。