简体   繁体   中英

Creating routes for Ajax calls in NodeJs

let's say I have this route for my rendered 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. I request the data when loading the page by sending a user id to the server and the server returns a user object:

$(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?

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.

So how can I define a route handling the page and the Ajax call?

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. You can fix this by moving your console.log statement into the done() callback like so:

$(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:

  • Create a separate api route to distinguish your API requests from your page requests. For example, app.get('/api/profile/:id, (req, res) => {...});'
  • Add a URL parameter to your AJAX calls specifying the format you want the response to be in, with the default being the page's HTML. For example, your AJAX would send a GET request to the URL /profile/2012?format=json , which would return the profile's information in JSON.

Personally, I prefer the first option, as it makes intent more clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM