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

时间:2017-05-14 14:45:12

标签: javascript node.js api reactjs local-storage

节点

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

反应

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

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

P.S:可能需要从反应发送到节点GET请求吗?

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

1 个答案:

答案 0 :(得分:0)

我假设您正在尝试与locastorage中保存的令牌一起发出请求。为此,您必须添加授权标头。喜欢

const token = localStorage.getItem('token')

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

获取令牌创建一个特定的路线 首先你需要导入
 import jwt from 'jwt-simple';

然后

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

其中SecretKey是为加密定义的密钥,这里带有时间的userId用于生成令牌