[英]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: 需要注意以下几点:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.