首页 文章

react-native - Bearer Token auth - httpReqest

提问于
浏览
1

我是初学者,我需要一些帮助 .

我正在编写一个用于android的应用程序with react native .

我已经实现了登录屏幕以及登录过程成功完成时应显示的所有屏幕 .

我不知道要向我的localhost网站发送带有bearer auth的http请求 . 请求方法是GET . 在我的应用程序中,我必须输入用户名和密码,并将其发送到https:/ localhost /.../登录 .

到目前为止这是有效的:我从loginscreen的TextInput获取了倾斜的用户和密码,并将它们发送到我的名为httpRequest的函数 .

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

// not implemented yet 

 }

我不知道如何开始...我应该从一个fetch-get mehtod开始,我可以在react-native docs上找到它?但是如何使用不记名令牌(auth)

2 回答

  • 0

    这是新手在处理身份验证时遇到的常见问题 .

    我建议你给这个好读https://auth0.com/blog/adding-authentication-to-react-native-using-jwt/

    你需要一些先进的知识来实现它,但无论如何你将学习它 .

  • 0

    您必须使用 POST 请求将您的用户名和密码发送到您的后端而不是 GET . 因此,您可以将名称和密码数据附加到请求正文 . 您还需要使用fetch来发出请求 .

    你可以这样做:

    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));
    
    }
    

    另外,请查看我对这个问题的答案,该问题是关于轻松生成 Headers 的fetch helper函数 . 它包含一个部分,可以轻松地为您的请求添加JWT令牌 .

    How to post a json array in react native

相关问题