javascript - React 前端获取http请求头信息

查看:1775
本文介绍了javascript - React 前端获取http请求头信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

背景:

前端通过react渲染页面,使用了react-slingshot,相当于是前端跑在一个node服务上面

需求:

需要通过客户端通过HTTP请求传递来的参数(header里放了token)进行用户权限的验证,比如访问
http://localhost:3000/rights/1,我需要拿到header中的token去验证用户是否登录,从而进行不同的渲染

问题:

如何通过每一次的路由获得http请求的头信息?或者在每次渲染组件时获得请求的信息?

代码:

html

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="language" content="zh">
        <meta name="format-detection" content="telephone=no">
        <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
        <title></title>
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>

index.js

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import routes from './routes';


const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
render(
  <Provider store={store}>
    <Router history={history} routes={routes} />
  </Provider>, document.getElementById('app')
);

Router

export default (
  <Route>
    <Route path="/rights/:id" component={Rights} />
    <Route path="/feeds/:id" component={Feeds} />
    <Route path="/articles/:id" component={Articles} />
  </Route>
);

解决方案

你用的是react-router做的是前端的路由,并没有向后端发送任何请求的。

如果后端用的node的话

app.get('*',function(req,res){
    //.....会在这里做后端路由拦截,从而达到前端路由的目的
})

每一次的路由获得http请求的头信息获得到的也是刚加载页面时,返回html的那个头部信息。

如果你的目的仅仅是为了做权限的话可以通过请求一条post协议获取当前权限信息。而服务端node可以通过对session的字段查找,判断权限的类型。返回给前端处理权限就可以,因为路由在前端你可以主动对路由进行重定向或者禁止跳转的操作

这篇关于javascript - React 前端获取http请求头信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆