【问题标题】:Why helmet blocks apollo api为什么头盔会阻止 apollo api
【发布时间】:2022-03-15 22:09:48
【问题描述】:

你能告诉我为什么头盔会在 localhost:4000/api 阻止 apollo api 吗?当我评论头盔时,它像以前一样工作正常。

您似乎处于离线状态。 POST 到此端点以查询您的图表:

curl --request POST
--header '内容类型:应用程序/json'
--url ''
--data '{"query":"query { __typename }"}'

const { ApolloServer } = require ('apollo-server-express');
const { ApolloServerPluginDrainHttpServer } = require  ('apollo-server-core');
const express= require ('express');
const http = require ('http');
const models = require('./models')
require ('dotenv').config();
const db = require('./db')
const DB_HOST = process.env.DB_HOST
const typeDefs = require('./schema')
const resolvers = require('./resolvers/index')
const jwt = require('jsonwebtoken');
const cors = require('cors')
const helmet = require('helmet')

db.connect(DB_HOST);


// get the user info from a JWT
const getUser = token => {
  if (token) {
    try {
      // return the user information from the token
      //console.log(jwt.verify(token, process.env.JWT_SECRET))
      return jwt.verify(token, process.env.JWT_SECRET);
    } catch (err) {
      // if there's a problem with the token, throw an error
      throw new Error('Session invalid');
    }
  }
};


async function startApolloServer(typeDefs, resolvers) {
  
  const app = express();
  app.use(cors())
  //app.use(helmet())
  const httpServer = http.createServer(app);

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    context: ({ req }) => {
      // get the user token from the headers
      const token = req.headers.authorization;
      // try to retrieve a user with the token
      const user = getUser(token);
      // for now, let's log the user to the console:
      //console.log(user);
      // add the db models and the user to the context
      return { models, user };
    },
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  });

  await server.start();
  server.applyMiddleware({ app,path: '/api' });
  await new Promise(resolve => httpServer.listen({ port: 4000 }, resolve));
  console.log(`???? Apollo Server ready at http://localhost:4000${server.graphqlPath}`);
  
  app.get('/', function (req, res) {
    res.send('Welcome in note app.')
  })
}

startApolloServer(typeDefs, resolvers)

【问题讨论】:

    标签: node.js graphql apollo-server


    【解决方案1】:

    要详细说明@Kraken 的答案,这就是您想要做的:

      const isDevelopment = appConfig.env === 'development'
    
      app.use(
        helmet({
          crossOriginEmbedderPolicy: !isDevelopment,
          contentSecurityPolicy: !isDevelopment,
        }),
      )
    

    【讨论】:

      【解决方案2】:

      app.use(helmet());

      是以下内容的别名:

      app.use(helmet.contentSecurityPolicy());
      app.use(helmet.crossOriginEmbedderPolicy());
      app.use(helmet.crossOriginOpenerPolicy());
      app.use(helmet.crossOriginResourcePolicy());
      app.use(helmet.dnsPrefetchControl());
      app.use(helmet.expectCt());
      app.use(helmet.frameguard());
      app.use(helmet.hidePoweredBy());
      app.use(helmet.hsts());
      app.use(helmet.ieNoOpen());
      app.use(helmet.noSniff());
      app.use(helmet.originAgentCluster());
      app.use(helmet.permittedCrossDomainPolicies());
      app.use(helmet.referrerPolicy());
      app.use(helmet.xssFilter());
      

      我遇到了同样的问题,所以我换掉了别名来分别添加每个别名。当我注释掉前两个(contentSecurityPolicy & crossOriginEmbedderPolicy)时,Apollo 复活了。

      为了记录,不建议在生产环境中注释掉这些政策,但它应该解除对卡在此处的任何人的阻止。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-16
        • 2011-05-20
        • 2011-03-27
        • 1970-01-01
        相关资源
        最近更新 更多