为什么头盔会阻止 apollo api

Sim*_*Z89 5 node.js graphql apollo-server

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

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

curl --request POST
--header '内容类型:application/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)
Run Code Online (Sandbox Code Playgroud)

Vla*_*tko 6

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

  const isDevelopment = appConfig.env === 'development'

  app.use(
    helmet({
      crossOriginEmbedderPolicy: !isDevelopment,
      contentSecurityPolicy: !isDevelopment,
    }),
  )
Run Code Online (Sandbox Code Playgroud)