Kurtis9
Kurtis9

Reputation: 117

Handling a success in JS

I am experimenting with t library, and am trying to install the functionality into my own search bar to practice (still a student).

Can anyone provide advice to the format this would be in??

Upvotes: 1

Views: 286

Answers (2)

turbopasi
turbopasi

Reputation: 3605

Completely ignoring what wappalyzer actually is or does, I would suggest the following, since you are already providing an async function as callback to your route controller :


app.get('/:url', async function (req, res) {
  
  try {

    await wappalyzer.init();
    const site = await wappalyzer.open(decodeURIComponent(req.query.url));
    const data = await site.analyze();

    // if you end up here, everything was successfull
    return res.status(200).json(data);

  } catch (ex) {
    
    // if you end up here, something went wrong
    return res.status(500).json({ message : ex.message });

  }

});

The above doesn't really make much sense, since you are telling your backend to look for an url param but using a query parameter instead. I woudln't recommend to send an url as either, param or query. Use the request body instead :

// receive request in backend, with an endpoint that makes a bit more sense
// also using POST method, otherwise you won't be able to send a body
app.post('/search', async function (req, res) {
  const url = req.body.url;
  // do stuff
});

// sending request to backend, using axios for example
const respond = await axios.post('/search', { url : 'www.google.com' });

// or using fetch
const respond = await fetch('/search', {
  method: 'post',
  body: JSON.stringify({ url : 'www.google.com' });

Please be aware these are just pointers, nothing to copy & paste :) .

If you are using Express, I suggest reading the documentation again. I think you are misunderstanding how the router works : https://expressjs.com/de/guide/routing.html#route-parameters

Upvotes: 3

ZAR
ZAR

Reputation: 2736

@PascalLamers answer is the cleanest way to go about it, using the "await" pattern.

To see what this looks like with promise chaining:

app.get('/:url', async function (req, res) {

  return wappalyzer
    .init()
    .then(function(){
       return wappalyzer.open(decodeURIComponent(req.params.url))
    })
    .then(function(site){
       return site.analyze()
    })
    .then(function(data){
       return res.status(200).json(data);
    })
    .catch(function(err){
      return res.status(500).json({ message : err.message })
    })
}

Each then executes a single async operation, and on success passes its result to the next then() operation.

Each then() is only called upon the success of the previous then(). If an error occurs at any point, the catch() is executed and the function returns (in this case, returns an error 500).

Upvotes: 3

Related Questions