Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you follow an HTTP Redirect in Node.js?

I want to open a page up in node and process the contents in my application. Something like this seems to work well:

var opts = {host: host, path:pathname, port: 80}; http.get(opts, function(res) {   var page = '';   res.on('data', function (chunk) {     page += chunk;   });   res.on('end', function() {      // process page   }); 

This doesn't work, however, if the page returns an 301/302 redirect. How would I do that in a reusable way in case there are multiple redirects? Is there a wrapper module on top of the http to more easily handle processing http responses from a node application?

like image 209
Zach Avatar asked Sep 06 '11 17:09

Zach


People also ask

How do you follow redirects?

To follow redirect with Curl, use the -L or --location command-line option. This flag tells Curl to resend the request to the new address. When you send a POST request, and the server responds with one of the codes 301, 302, or 303, Curl will make the subsequent request using the GET method.

How do I redirect in NodeJS?

NodeJS redirect using Express framework. To perform a redirect using Express framework, you simply need to send a response using the redirect() method provided by the framework.

How does HTTP redirect work?

In HTTP, redirection is triggered by a server sending a special redirect response to a request. Redirect responses have status codes that start with 3 , and a Location header holding the URL to redirect to. When browsers receive a redirect, they immediately load the new URL provided in the Location header.

Can Axios handle redirect?

To make redirects after an axios post request with Express and React, we set window. location to the new URL value after the response from the axios request to the Express back end is available.


2 Answers

If all you want to do is follow redirects but still want to use the built-in HTTP and HTTPS modules, I suggest you use https://github.com/follow-redirects/follow-redirects.

yarn add follow-redirects npm install follow-redirects 

All you need to do is replace:

var http = require('http'); 

with

var http = require('follow-redirects').http; 

... and all your requests will automatically follow redirects.

With TypeScript you can also install the types

npm install @types/follow-redirects 

and then use

import { http, https } from 'follow-redirects'; 

Disclosure: I wrote this module.

like image 146
Olivier Lalonde Avatar answered Sep 20 '22 22:09

Olivier Lalonde


Is there a wrapper module on top of the http to more easily handle processing http responses from a node application?

request

Redirection logic in request

like image 43
Raynos Avatar answered Sep 23 '22 22:09

Raynos