[英]Request data using jQuery from a NodeJS server
我有以下客戶端代碼(在瀏覽器或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端點以及一個有關如何實現URL路由的html頁面 。
所有人都說過,我建議您看一下庫expressjs: http ://expressjs.com/starter/basic-routing.html。 它在很大程度上簡化了路由管理並提供了更多功能。
希望這對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.