【问题标题】:React:: Error: GraphQL error: Cannot read property 'headers' of undefinedReact:: 错误:GraphQL 错误:无法读取未定义的属性“标题”
【发布时间】:2020-07-25 19:54:27
【问题描述】:

我在 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。

【问题讨论】:

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


    【解决方案1】:

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

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

    检查您的代码中的上述行,当您已经在 authHeader 常量中拥有它时,为什么您甚至需要它。

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

    【讨论】:

      【解决方案2】:

      问题可能在于您在 Apollo 服务器中转发请求对象的方式。确保它是这样的:

      const server = new ApolloServer({
        typeDefs,
        resolvers,
        context: ({ req }) => ({req}),  // LIKE THIS
        context: ({ req }) => req,      // NOT LIKE THIS, Results in undefined req
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-22
        • 2019-11-04
        • 2023-03-03
        • 2021-09-03
        • 2020-01-20
        • 2021-06-11
        • 2022-01-03
        • 1970-01-01
        相关资源
        最近更新 更多