【发布时间】:2019-06-26 08:52:07
【问题描述】:
所以我正在迁移到 apollo-server-express 2.3.3(我使用的是 1.3.6) 我遵循了几个指南,进行了必要的调整,但陷入了 CORS 问题。
根据docs,您必须使用 applyMiddleware 函数将 apollo 服务器与 express 连接起来。
我目前正在做以下事情:
const app = express();
// CORS configuration
const corsOptions = {
origin: 'http://localhost:3000',
credentials: true
}
app.use(cors(corsOptions))
// Setup JWT authentication middleware
app.use(async (req, res, next) => {
const token = req.headers['authorization'];
if(token !== "null"){
try {
const currentUser = await jwt.verify(token, process.env.SECRET)
req.currentUser = currentUser
} catch(e) {
console.error(e);
}
}
next();
});
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({ Property, User, currentUser: req.currentUser })
});
server.applyMiddleware({ app });
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
})
由于某种原因,我的 express 中间件似乎没有执行,当我尝试从 localhost:3000(客户端应用程序)发出请求时,我收到典型的 CORS 错误
使用 apollo-server-express 1.3.6,我可以毫无问题地执行以下操作:
app.use(
'/graphql',
graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }),
bodyParser.json(),
graphqlExpress(({ currentUser }) => ({
schema,
context: {
// Pass Mongoose models
Property,
User,
currentUser
}
}))
);
现在有了新版本,尽管文档使这看起来像一个简单的迁移,但我似乎无法让它工作。我查看了各种文章,似乎没有人遇到问题。
【问题讨论】:
标签: node.js express graphql apollo-server