[英]Creating routes for Ajax calls in NodeJs
假設我的渲染HTML具有以下路線:
app.get('/profile/:id', function (req, res) { // my route
res.render('profile', { id: Number(req.params.id) }); // render the file and set a variable
});
並在我的個人資料頁面的客戶端javascript文件中,我想從服務器獲取數據。 加載頁面時,我通過向服務器發送用戶ID來請求數據,並且服務器返回用戶對象:
$(document).ready(function() {
var user = null;
$.ajax({
type: 'GET',
url: '', // This one is missing here
dataType: 'json'
}).done(function(data){
user = JSON.stringify(data);
});
console.log(user.name);
});
我的服務器將處理此功能:
app.get('', function (req, res) { // missing route
var userId = ; // This is missing
var userObj = getUserById(userId);
res.send(userObj);
});
我必須使用什么路線? 教程說我必須通過/profile/:id
這樣的路由,但是該路由已經存在?
我嘗試定義一條新路線,例如:
app.get('/reqUser/:id', function (req, res) { // Ajax route
res.send(getUserById(Number(req.params.id)));
});
對於我的Ajax調用,我傳入了URL http://localhost:8888/reqUser/12345
但這似乎是錯誤的,因為使用Ajax調用后用戶仍然為null。
那么,如何定義處理頁面和Ajax調用的路由?
編輯:首先,您將要修復客戶端JS中的錯誤,在該錯誤中,您嘗試在從服務器中獲取user
之前打印user.name
。 您可以通過將console.log
語句移至done()
回調中來解決此問題,如下所示:
$(document).ready(function() {
var user = null;
$.ajax({
type: 'GET',
url: '', // This one is missing here
dataType: 'json'
}).done(function(data){
user = JSON.stringify(data);
console.log(user.name); // log here
});
});
關於您的路線問題,您有幾種選擇。 以下是此問題的兩種常見解決方案:
api
路由,以區分您的API請求和頁面請求。 例如, app.get('/api/profile/:id, (req, res) => {...});'
/profile/2012?format=json
,該請求將以JSON返回配置文件的信息。 就個人而言,我更喜歡第一種選擇,因為它可以使意圖更清晰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.