Note that there are some explanatory texts on larger screens.

plurals
  1. POCan Express alter incoming requests and redirect to a different method after alteration?
    text
    copied!<p>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:</p> <pre><code>app.get('/predict', function(req, res) { // req.query should be something like // { name: "wat", id: 123 } res.render('predictions'); } </code></pre> <p>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".</p> <p>In my mind, I want to extend the above endpoint to do something like</p> <pre><code>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'); } } </code></pre> <p>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.</p> <p>Now we get to the question. Can I do something like this?</p> <pre><code>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+'&amp;id='+bestMatchId); } } else { // some code res.render('predictions'); } } </code></pre> <p>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.</p> <p>Is this possible/wise/safe? Am I missing something?</p> <p>Big thanks in advance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload