Search code examples
node.jshttphttp-redirectrequestapi-design

how can I get an element in a redirect url using node.js


Non-English country, please forgive my spelling mistakes.

For example, I want to first redirect url1(http://localhost:3000/api/song/167278) to url2(http://localhost:4000/api/song/167278) to use url2's api. And url2 will reponse a json file, which can be seen in the postman's panel.

(postman's pannel)

But there maybe a lot of elements, I only want an element in the file, such as data[0].url. How can I return just return the url value (data[0].url in this json) when people access http://localhost:3000/api/song/167278.

I am using express.js now, how can I edit it? Or is there any other methods?

app.get('api/song/:id', async (req, res) => {
  try {
    const { id } = req.params
    url = "http://localhost:4000/api/song/" + id
    res.redirect(url)
  }
  catch (e) {
    console.log(e)
  } 
}

Solution

  • You could either proxy the entire request there or fetch localhost:4000/api/song/1 in your request handler (with something like node-fetch or axios or with node's APIs and send the fields that you want back to the client as json.