使用中间件时无法访问请求的“授权”字段

时间:2019-07-09 10:51:02

标签: node.js reactjs jwt authorization graphql

我正在尝试创建一个登录页面,但是我不太了解如何使用jwt。我遵循了有关Youtube的教程,但是在创建中间件时遇到了麻烦,必须访问请求的“授权”字段。为什么“ req.get('Authorization')”返回未定义?

------------------中间件----------------------


module.exports = (req,res,next) => {
  const authHeader = req.get('Authorization');
  console.log(req.headers)
  if (!authHeader) {
    req.isAuth = false;
    return next();
  }
  const token = authHeader.split(' ')[1];
  if (!token || token === '') {
    req.isAuth = false;
    return next();
  }
  let decodedToken;
  try {
    decodedToken = jwt.verify(token, 'somesupersecretkey');
  } catch (err) {
    req.isAuth = false;
    return next();
  }
  if (!decodedToken) {
    req.isAuth = false;
    return next();
  }
  req.isAuth = true;
  req.userId = decodedToken.userId;
  next();
  }

------------- GraphQL Schema的一部分------------------

  Login : {
      type: AuthType,
      args : {
        email: {type:GraphQLString},
        password: {type:GraphQLString}
      },
     async resolve(parent,args,req){
        await console.log(args.email)
        const user = await UserModel.findOne({ email: args.email });
        if (!user) {
        throw new Error('User does not exist on login!');
        }
        const isEqual = await bcrypt.compare(args.password, user.password);
        if (!isEqual) {
        throw new Error('Password is incorrect!');
        }
        const token = jwt.sign(
        { userId: user.id, email: user.email },
        'somesupersecretkey',
        {
        expiresIn: '1h'
        }
        );


        return {tokenExpiration: 1, userId: user.id, token:token}
    }
 }

------------- React组件--------------

static contextType = AuthContext;

   render(){
        return (
          <ApolloConsumer>
           {client => {
                   return ( <form>
                     <label>Email</label><br/>
                     <input type="text" onChange={(e) => this.setState({email:e.target.value})}/><br/>
                     <label>Password</label> <br/>
                     <input type="text" onChange={(e) => this.setState({password:e.target.value})}/><br/>
                     <input typr="submit" value="Login" onClick={async ()=>{
                      try {
                        const data = await client.query({query:Login,variables:{email:this.state.email,password:this.state.password}})
                        this.context.login(data.data.Login.userId,data.data.Login.token)
                      } catch(err) {
                        throw err
                      }
                     }}/>
                     </form>)
                     }}
           </ApolloConsumer>
    )
  }

---查询---

const Login = gql`
query ($email:String!,$password:String!){
   Login(email:$email,password:$password){
     token
     userId
   }
}
`

0 个答案:

没有答案