【发布时间】: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