[英]Creating routes for Ajax calls in NodeJs
let's say I have this route for my rendered HTML: 假设我的渲染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
});
and in my client side javascript file for the profile page I want to get data from the server. 并在我的个人资料页面的客户端javascript文件中,我想从服务器获取数据。 I request the data when loading the page by sending a user id to the server and the server returns a user object:
加载页面时,我通过向服务器发送用户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);
});
And my server would handle this function: 我的服务器将处理此功能:
app.get('', function (req, res) { // missing route
var userId = ; // This is missing
var userObj = getUserById(userId);
res.send(userObj);
});
What route do I have to use? 我必须使用什么路线? Tutorials say I have to pass in the route like
/profile/:id
but this route already exists? 教程说我必须通过
/profile/:id
这样的路由,但是该路由已经存在?
I tried defining a new route like: 我尝试定义一条新路线,例如:
app.get('/reqUser/:id', function (req, res) { // Ajax route
res.send(getUserById(Number(req.params.id)));
});
and for my Ajax call I pass in the url http://localhost:8888/reqUser/12345
but this seems to be wrong because user is still null after using the Ajax call. 对于我的Ajax调用,我传入了URL
http://localhost:8888/reqUser/12345
但这似乎是错误的,因为使用Ajax调用后用户仍然为null。
So how can I define a route handling the page and the Ajax call? 那么,如何定义处理页面和Ajax调用的路由?
Edit: First off, you'll want to fix the bug in your client-side JS, where you are attempting to print user.name
before user
has been fetched from the server. 编辑:首先,您将要修复客户端JS中的错误,在该错误中,您尝试在从服务器中获取
user
之前打印user.name
。 You can fix this by moving your console.log
statement into the done()
callback like so: 您可以通过将
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
});
});
Regarding your routes question, you have several options. 关于您的路线问题,您有几种选择。 Below are two common solutions to this problem:
以下是此问题的两种常见解决方案:
api
route to distinguish your API requests from your page requests. api
路由,以区分您的API请求和页面请求。 For example, app.get('/api/profile/:id, (req, res) => {...});'
app.get('/api/profile/:id, (req, res) => {...});'
/profile/2012?format=json
, which would return the profile's information in JSON. /profile/2012?format=json
,该请求将以JSON返回配置文件的信息。 Personally, I prefer the first option, as it makes intent more clear. 就个人而言,我更喜欢第一种选择,因为它可以使意图更清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.