1

I'm new to react native and I need some help.

I'm writing an app for android with react native.

I had already implemented the login Screen and all screens that should be shown when the loggin process completed successfully.

I don't know to to make a http request with bearer auth to my localhost website.The Request Method is GET. In my app i have to enter username and password and send it to the https:/localhost/.../login.

This is working so far: I get the tipped user and password from the TextInput of the loginscreen and send both to my function called httpRequest.

function httpRequest(name, password) {
var httpResponse = null;

// not implemented yet 

 }

I don't know know how to start ... should i start with a fetch-Get mehtod that i can find on react-native docs ? But how should i do it with bearer token (auth)

Computer's Guy
  • 5,122
  • 8
  • 54
  • 74
Vitja
  • 21
  • 1
  • 7

2 Answers2

1

This is a common issue newcomers face when dealing with authentication.

I recommend you to give this a good read https://auth0.com/blog/adding-authentication-to-react-native-using-jwt/

You need a bit of advanced knowledge to implement it but you will learn with it, anyways.

Computer's Guy
  • 5,122
  • 8
  • 54
  • 74
0

You'll have to send your username and password to your backend with a POST request NOT a GET. So you can attach the name and password data to the body of the request. Also you'll want to use fetch to make the request.

You can do it like this:

function httpRequest(name, password) {

  const user = {
    name,
    password,
  };

  fetch('https://mywebsite.com/endpoint/', {
    method: 'post',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(user)
  })
    .then(res => res.json())
    .then(data => {
      console.log(data);
      // data should contain a JWT token from your backend
      // which you can save in localStorage or a cookie
    })
    .catch(err => console.log(err));

}

Also check out my answer on this question about a fetch helper function for easily generating headers. It includes a piece in there for easily adding a JWT token to your requests.

How to post a json array in react native

Community
  • 1
  • 1
Tyler Buchea
  • 1,642
  • 3
  • 17
  • 25