How to know the url that I will be redirected to? [nodejs] [node-fetch]
Asked Answered
J

2

8

I am trying to load a JSON file from a url in google cloud. I am using the node-fetch package and it works fine for a couple of hours. The problem is that google changes the redirected url frequently. How can I make a get request to the url I will be forwarded to? Or at least know what url I will be forwarded to? I see there is also a package called request, but its deprecated.

This is the code

var express = require('express');
var router = express.Router();
var fetch = require('node-fetch');

router.get('/', async (req, res) => {
  
  const url = 'https://storage.cloud.google.com/blablabla/config.json';

  fetch(url)
    .then((fetchRes) => {
      if (fetchRes.ok) {
        return fetchRes.json();
      }
    })
    .then((data) => res.send({ data }))
    .catch((err) => res.send(err));
});

module.exports = router;
Justifier answered 24/6, 2020 at 16:59 Comment(3)
I abandoned this approach and saved this json file locally since its pretty tiny. I suppose thr0n's answer would work!Justifier
node-fetch follows redirects by default (github.com/node-fetch/node-fetch#options). Note, you are overwriting 'res' as set by router with the fetch response. 'res'Gladstone
@Gladstone ah yeah thanks I changed this. To be honest this is a very old project I have no idea why it wasn't working if node follows redirects by default...Justifier
F
5

The Response object has an undocumented url property. So, let's say you call

const response = await fetch(url, {
    redirect: 'follow',
    follow: 10,
});

response.url will be the URL of the last redirect that was followed.

Frisbee answered 23/3, 2022 at 22:13 Comment(0)
L
3

You can look up the final URL in the response headers. In your case res.headers.get('location') should do the trick.

Leatherworker answered 24/8, 2020 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.