0

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)
  } 
}
gricn
  • 63
  • 12
  • 1
    Update the question what you want exactly so that we can easily help you – Mahesh G Mar 12 '20 at 16:59
  • You could either [proxy](https://github.com/villadora/express-http-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](https://nodejs.dev/making-http-requests-with-nodejs) and send the fields that you want back to the client as json. – cbr Mar 12 '20 at 18:58
  • @cubrr Thanks, bro. I use fetch to get the fields. Write an answer and I adopt it. – gricn Mar 13 '20 at 01:28
  • Sure thing! I'm glad I could help! – cbr Mar 13 '20 at 09:15
  • I have troubled in it for 5 hours. And I got the solution within 3 hours after post in Stack Overflow. Happy! Thanks you very much! – gricn Mar 13 '20 at 10:04

1 Answers1

0

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.

cbr
  • 12,563
  • 3
  • 38
  • 63