简体   繁体   English

需要将从后端(json)发送的Access令牌存储到localstorage并使用该令牌登录。 怎么样?

[英]Need to Store a Access token send from backend (json) into localstorage and login using that token. How?

I am trying implement a login (Plain Javascript). 我正在尝试实现登录(普通Javascript)。 I am getting a Token from backend. 我从后端得到一个令牌。 I need to make the login using that token and storing it in LocalStorage. 我需要使用该令牌进行登录并将其存储在LocalStorage中。 Please help me on this. 请帮帮我。

I have done the API call correctly. 我已正确完成API调用。 But I am getting a 502 (Bad Gateway) error. 但是我收到了502(Bad Gateway)错误。 I think the reason is I am not setting the token. 我认为原因是我没有设置令牌。

function postData() {
    var res = fetch('https://example.api.com/login', {
        method: "POST", // POST
        mode: "cors",
        cache: "no-cache",

        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Access-Control-Allow-Origin': '*',
            'Accept': 'application/json'    
        },

        redirect: "follow",
        referrer: "no-referrer",


        body: JSON.stringify({
            isArray: false,
            data: {
                    email: document.getElementById("email").value,
                    password: document.getElementById("passwordNew").value
                }
        })

    }).then(response => response.json()); // parses response to JSON
    console.log("result :" + res);
    return res;
}

This is the API call I make and as the response I get the token. 这是我发出的API调用,也是我获得令牌的响应。

Response is mentioned below. 回应如下。

"data": {
    "token": "sdfsdgsfgsgsgssb497e7764f4df8cb504a122cc18b2eed8",
    "startTime": 1558417495078,
    "endTime": 1558503895078
}

I expect to successfully login after entering email and password - Using the token sending from the backend. 我希望在输入电子邮件和密码后成功登录 - 使用从后端发送的令牌。

So once you receive the token back from your login request, you need to store your token. 因此,一旦从登录请求中收到令牌,您就需要存储令牌。 Looks like you are on the right track, thinking about localStorage. 看起来你走在正确的轨道上,想着localStorage。 Also, I'd recommend going ahead and using the async/await syntax as its much easier to read / use. 另外,我建议继续使用async / await语法,因为它更容易阅读/使用。 It requires you to leverage promises, but it much more readable. 它要求您利用承诺,但它更具可读性。 And rather than resolve / reject functions, you just wrap your code in try/catch blocks. 而不是解析/拒绝函数,您只需将代码包装在try / catch块中。 So to store your token in localStorage after login, do something like this: 因此,要在登录后将令牌存储在localStorage中,请执行以下操作:

async function handleLogin(un, pw) {
  try {
    let response = await fetch('https://example.api.com/login', {
        method: "POST", // POST
        mode: "cors",
        cache: "no-cache",
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Access-Control-Allow-Origin': '*',
            'Accept': 'application/json'    
        },
        redirect: "follow",
        referrer: "no-referrer",
        body: JSON.stringify({
            isArray: false,
            data: {
                    email: document.getElementById("email").value,
                    password: document.getElementById("passwordNew").value
                }
        })
    })
    response = response.json();
    window.localStorage.setItem('token', response.data.token)
  } catch(e) {
    console.log('error while logging in', e)
  }
}

Then when you want to use your token in future requests, you grab it from localStorage. 然后,当您想在将来的请求中使用您的令牌时,您可以从localStorage中获取它。 For example: 例如:

async function editProfile(updatedProfileInfo) {
  const token = localStorage.getItem('token');
  try{
    let response = await fetch('https://someurl.com/edit', {
      method: "POST",
      ...
      'x-access-token': token,
      ...
    })
  //handle response
  } catch(e) {}
}

A few things to take note of: 需要注意以下几点:

  1. Make sure you know how your API expects tokens to be bundled in requests. 确保您知道您的API如何将请求中的令牌捆绑在一起。 In the example above, I stick it in the x-access-token section of the request header. 在上面的示例中,我将其粘贴在请求标头的x-access-token部分中。 However, many people use cookies, etc. Make sure you are passing it where it is expected. 但是,许多人使用cookies等。确保您将其传递到预期的位置。
  2. Before making the request, it is often customary to check if the token is still valid or if it has expired. 在发出请求之前,通常会检查令牌是否仍然有效或是否已过期。 As such, maybe it makes sense to also store your entire login response, which includes expiration info and endtime. 因此,也可以存储整个登录响应,包括过期信息和结束时间。 Then you can do the check before making the ajax call, and just log the user out if the token is invalid. 然后,您可以在进行ajax调用之前进行检查,如果令牌无效,则只需将用户注销。 When you do this, be sure to remove the token from localStorage as well. 执行此操作时,请务必从localStorage中删除该令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NextJS如何在localStorage中存储token - NextJS how to store token in localStorage 如果 localstorage access_token 未定义,如何重定向回登录页面 - How to redirect back to login page if localstorage access_token is undefined OAuth2刷新令牌。 如何在客户端存储它 - OAuth2 Refresh Token. How to store it on client-side 使用 Axios 向后端发送令牌 - Using Axios to send a token to the backend 如何使用 axios 将响应重新验证令牌发送到后端 - how to send response recaptcha token to backend using axios 如何在 Angular 8 中存储像 jwt 令牌这样的数据? 是否有另一种使用本地存储或会话存储安全存储的方法? - How to store data like jwt token in Angular 8? Is there another way to store safely using localstorage or session storage? 禁止(CSRF 令牌丢失或不正确。)如何将 CSRF 令牌从前端发送到后端? - Forbidden (CSRF token missing or incorrect.) how to send CSRF token from frontend to backend? 如何使用 vue 在 django 后端发送 firebase 令牌? - how to send the firebase token at the django backend with vue? 如何使用localStorage通过令牌正确连接到Horizo​​n? - How to connect to Horizon with a token properly using localStorage? 如何在邮递员中发送访问令牌 - How to send access token in postman
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM