简体   繁体   English

如何从节点数据发送到localStorage React?

[英]How to send from node data to localStorage React?

node 节点

const LocalStorage = require ('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./localStorage');
localStorage.setItem('username', user.name);
localStorage.setItem('token', user.token)

react 应对

const author = localStorage.getItem('username')
const token = localStorage.getItem('token')

In react console.log(localStorage) // {} 在react console.log(localStorage)// {}中

PS: maybe need send from react to node GET request? PS:也许需要从响应发送到节点GET请求?

  fetch('/api', {
    method: 'GET'

I Assume that you are trying to make request along with the token that you have saved in locastorage . 我假设您正在尝试与已保存在locastorage的令牌一起发出请求。 for that you have to add Authorization headers. 为此,您必须添加授权标头。 like 喜欢

const token = localStorage.getItem('token')

fetch('https://example.com/endpoint', {
  method: 'GET',
  headers: {
    'Authorization': token
  }  
})

to get the token create a specific route like first you need to import 要获得令牌,请先创建一条特定的路线,例如首先需要导入
import jwt from 'jwt-simple';

Then 然后

app.post('/login',function(req,res,next){
   res.send({token:jwt.encode({sub:user.id,iat:timpestamp},SecretKey)});
});

where SecretKey is the key defined to encryption and here the userId with time is taken to generate the token 其中SecretKey是定义为加密的密钥,此处带时间的userId用于生成令牌

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM