Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the user-agent in react native fetch api

I have tried to change the user agent in react native fetch API:

const URLENCODED_HEADER = {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'User-Agent': Platform.OS + "/" + DeviceInfo.getUniqueID().toString()
}

export async function doRegister(secureInfo) {
  formBody = encodeParameters(secureInfo)
  try {
    let response = await fetch(SERVER_URL+'/user/register', {
      method: "POST",
      headers: URLENCODED_HEADER,
      body: formBody,
      credentials: 'include'
    });
    let responseJson = await response.json();
    return responseJson;
  } catch(error) {
    console.error(error);
    throw error;
  }
}

I have also checked the requests' header in Reactotron: enter image description here

And it shows the correct information I want.

However, on the server side, the ua is still the default for android and ios devices:

Mozilla/5.0 (iPad; CPU OS 11_2_6 like Mac OS X) AppleWebKit/604.5.6 (KHTML, like Gecko) Version/11.0 Mobile/15D100 Safari/604.1

okhttp/3.6.0

Dalvik/2.1.0 (Linux; U; Android 5.1.1; Coolpad 3622A Build/LMY47V)

Is it possible to change the user-agent for requests sent in react-native and how if so?

like image 557
bleepmeh Avatar asked Mar 21 '18 20:03

bleepmeh


1 Answers

Try to Stop Remote JS Debug to test it.

I was dealing with the same problem too. It worked for me. :)

Some notes:

  1. it's only for React Native
  2. React Native already has a default User-Agent. Something like: <PROJECT_NAME>/<VERSION> CFNetwork/975.0.3 Darwin/17.7.0
  3. while using Remote JS Debugging, it'll use the browser user-agent. Something like: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
like image 108
Erick M. Sprengel Avatar answered Oct 05 '22 01:10

Erick M. Sprengel