Sunday, 4 June 2017

How to call third party API inside a controller function in Node/Express?

Just playing around with my first Node/Express App.

What I am trying to do:

On submitting a form to /wordsearch (POST) the Wikipedia API should be called with the submitted keyword. After getting back the response from Wikipedia, I want to present it back to the user in a view. Basic stuff. But I am missing some basic understanding of how to arrange that in NODE/JS. I read about callbacks and promises lately and understand the concepts theoretically, but seem to mix things up when trying to put it into code. If someone could shed light on where I am wrong, that would be highly appreciated.

Approach 1:

This is the controller function that is hit on submitting the form:

exports.searchSources = (req, res) => {
  const term = req.body.searchTerm

  const url = `https://en.wikipedia.org/w/api.php?action=opensearch&search=${term}&limit=10&namespace=0&format=json`
  const client = new Client()

  client.get(url, function (data, response) {
    //this causes the error
    res.json(data)
  })  
}

=> Error: Can't set headers after they are sent.

I know, that the error stems from trying to set response headers twice or when the response is already in a certain state, but I don't see where that happens here. How can I wait for the result of the Wiki request and have it available in the controller function so that I can render it?

Approach 2:

Again, the controller function:

exports.searchSources = (req, res) => {
  const term = req.body.searchTerm

  const url = `https://en.wikipedia.org/w/api.php?action=opensearch&search=${term}&limit=10&namespace=0&format=json`
  const client = new Client()

  const data = client.get(url, function (data, response) {
    return data
  })

  res.json(data)
}

=> TypeError: Converting circular structure to JSON at JSON.stringify ()

This was just a try to make the response from Wiki available in the controller function.



via Flip

No comments:

Post a Comment