I have an Express (v3) app where (in an ideal scenario) a user types a string into an input field, waits for an autocomplete function to return a list matching the string, and chooses from that list, thereby adding an 'id' value to a hidden field. When they click 'Go', their request is routed to this endpoint with their query:
app.get('/predict', function(req, res) {
// req.query should be something like
// { name: "wat", id: 123 }
res.render('predictions');
}
I want to change this functionality slightly, so that if the req.query.id is empty (i.e. the user didn't wait for the autocomplete), I don't have to redirect them back saying "Please wait for the autocomplete".
In my mind, I want to extend the above endpoint to do something like
app.get('/predict', function(req, res) {
// req.query is { name: 'wat', id: '' }
if(req.query.id=='') {
// then the user didn't wait for the autocomplete, so
// guess the id ourselves
} else {
// ... some code
res.render('predictions');
}
}
In guessing the ID for myself, I'm using the same external API as I use for my autocomplete function, which returns an array of results with confidence values based on a query parameter, i.e. how likely it thinks the result is what I want.
Now we get to the question. Can I do something like this?
app.get('/predict', function(req, res) {
// req.query is { name: 'wat', id: '' }
if (req.query.id=='') {
makeRequestToAPIWithQuery(req.query.name, function(err, suggestions) {
// suggestions[0] should contain my 'best match'
var bestMatchName = suggestions[0].name;
var bestMatchId = suggestions[0].id;
// I want to redirect back to *this* endpoint, but with different query parameters
res.redirect('/predict?name='+bestMatchName+'&id='+bestMatchId);
}
} else {
// some code
res.render('predictions');
}
}
I want the server to make a different request to itself if req.query.id is empty. So after the redirect, req.query.id shouldn't be empty and res will render my 'predictions' view as required.
Is this possible/wise/safe? Am I missing something?
Big thanks in advance.