Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force to use different user agent with js or axios

I am routing all requests through my axios get and post requests. I am testing some iframes which detect the user agent and depending on what agent it is, they change the payload and the style etc.

If I change it on dev tools by toggling device toolbar and setting to an iphone for example, all requests are coming with the correct user agent and all works good, nothing gets blocked, but if I pass my own user agent (the same which I copied from the ones being used by the device toolbar) and pass it as a custom axios header it kind of works but not really. The iframe detects its a device but requests are still blocked.

Is there a way to force to use another user agent via js or axios?

Currently I am using axios like this:

axios.get(req.originalUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1' }  }).then((response) => {
      res.send(response.data)
    })
like image 397
AlwaysConfused Avatar asked Nov 01 '20 10:11

AlwaysConfused


People also ask

Is Axios good for Nodejs?

Axios is a very popular JavaScript library you can use to perform HTTP requests, that works in both Browser and Node. js platforms. It supports all modern browsers, including support for IE8 and higher. It is promise-based, and this lets us write async/await code to perform XHR requests very easily.

Is Axios asynchronous?

Axios is a promise based HTTP client for the browser and Node. js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.

Is Axios A third party library?

It is a third-party tool (not Vanilla JavaScript) that can be used on both the client and server sides. One major aspect of Axios to be aware of is that it is not natively provided by the browser to JavaScript, it must be installed and imported (dependency) to be available for use.


Video Answer


1 Answers

Yes, we can set user-agent with requests we're making by passing additonal arguments options to an axios call.

let options = {
  headers: {
    'User-Agent': 'xyz-bla-bla'
  }
}

axios.get(req.originalUrl, data, options);   // setting request header, using options

//or 

axios.get(req.originalUrl, data, options).then((response) => {
  //res.header({'key':'value'})     //set response header, if necessary
  res.send(response.data);
});

Remember to distinguish between response header, and request header.

like image 52
kishore Avatar answered Oct 03 '22 04:10

kishore