[英]how send server data in a multi page web application?
这些天我做了一个标准的主页、一个登录页面和一个用户信息页面。 在我使用 POST 和 Ajax(Fetch) 方法的登录页面中,我将电子邮件和密码发送到服务器,服务器使用属于该电子邮件的用户信息响应正确的 json。 但我不知道 JSON 中的用户信息如何在另一个 HTML 文档(如用户信息页面)中使用。 我尝试了很多东西,但没有任何帮助。
form.addEventListener('submit',(e)=>{
e.preventDefault();
const data={}
data1.correo=email.value;
data1.contrasenia=password.value;
const miinit={
method:'POST',
headers: {"Content-type":"application/json"},
body:JSON.stringify(data1)}
const url='https://localhost:44351/api/login';
const myrequest =new Request(url,miinit)
const requestpost=()=>{
fetch(myrequest).then(response=>{console.log(response);return response.json()}).then(response=>{console.log(response)})
}
requestpost()
})
如果要在多个页面中使用从服务器返回的信息,则必须将其存储在LocalStorage或其他持久性 API 中。 数据不会跨页面共享。
我假设你在没有任何图书馆或任何东西的情况下做这一切。 话虽如此,我假设每个页面转换都将是一个完整的页面刷新。 这意味着 API 返回的对象仅与登录页面的生命周期一样好。
您有两个选项可用于您的设置:
localStorage
存储当前用户的 JSON 负载。 const payload = { userId: 1, name: 'Test' }; // The item being saved to localStorage must be // a string. You serialize/deserialize as your // set/get if need be. localStorage.setItem('currentUser', JSON.stringify(payload)); // On some other page, calling localStorage.getItem // will give you the object console.log(localStorage.getItem('currentUser'));
getCurrentUser
方法,这将返回登录的用户。这两个选项都有需要考虑的安全点,但这不是这个问题的内容。 我认为对您来说,最简单的选择是将对象保存到本地存储,但我不建议将其用于生产设置。 如果您正在尝试做一些生产就绪的事情,我建议您研究 JWT 身份验证。
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.