反应::错误:GraphQL错误:无法读取未定义的属性“标头”

时间:2020-04-13 09:20:49

标签: reactjs graphql apollo react-apollo apollo-server

我在netlify上部署了我的应用。

在本地服务器上,我可以发表评论。

但是在生产模式下,

“错误:GraphQL错误:无法读取未定义的属性'headers'” 在我提交评论时出现。

我尝试了多种方法来解决此问题,但无法解决。

我认为问题是我在Heroku上的GraphQL服务器。

check-auth.js

const { AuthenticationError } = require('apollo-server');

const jwt = require('jsonwebtoken');
const { SECRET_KEY } = require('../config');

module.exports = (context) => {
  // context = { ... headers }
  const authHeader = context.req.headers.authorization;

  if (authHeader) {
    // Bearer ....
    const token = req.headers.authorization || '';
   //I tried. const token = req.headers["authorization"];
    if (token) {
      try {
        const user = jwt.verify(token, SECRET_KEY);
        return user;
      } catch (err) {
        throw new AuthenticationError('Invalid/Expired token');
      }
    }
    throw new Error("Authentication token must be 'Bearer [token]");
  }
  throw new Error('Authorization header must be provided');
};

只有登录的用户可以发表评论。

用户登录后,我的用户ID存储在本地服务器中。 密钥是jwtToken。

2 个答案:

答案 0 :(得分:0)

是错字还是您在获取令牌时实际上错过了上下文对象?

const token = context.req.headers.authorization || ''; 

检查代码中的上一行,为什么当您已经在authHeader常量中拥有该代码时,为什么还要使用它呢?

理想情况下,您的令牌将位于context.req.headers ['x-token']或req.headers ['token']中,具体取决于您通过的方式。

答案 1 :(得分:0)

问题可能与您在Apollo服务器中转发请求对象的方式有关。确保它读取的内容如下:

<div id="root">
  <div><button class="b1">Hello</button><button class="b1"><svg viewBox="0 0 24 24" stroke-width="2" stroke="black" stroke-linecap="round" stroke-linejoin="round" class="s1"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg></button></div>
</div>