In the apollo-server-micro package, the CORS example is incorrect because Apollo Server will respond with status code 405 for OPTIONS requests. To avoid this, a simple fix is to use the following code instead:
module.exports = cors((req, res) => {
if (req.method === 'OPTIONS') {
res.end()
return
}
return server.createHandler()(req, res)
})
I think this would be better fixed in the implementation rather than a docs change. This was fixed in the lambda implementation here:
Just a heads up for anyone else who stumbles across this problem. Here is the code that worked for my server.
import micro from 'micro';
import cors from 'micro-cors';
import { ApolloServer } from 'apollo-server-micro';
const server = new ApolloServer({/* config */});
const optionsHandler = (req: IncomingMessage, res: ServerResponse) => {
if (req.method === 'OPTIONS') {
res.end();
return;
}
return server.createHandler()(req, res);
};
const microserver = micro(cors()(optionsHandler));
export default microserver.listen({ port: config.port }, () => {
const plaground = server.graphqlPath;
console.log(`๐ Server: http://localhost:${config.port}${plaground}`);
console.log(`๐ Environment: ${config.environment}`);
console.log(`๐ Production: ${config.production}`);
});
Hope it helps!
maybe implement here?
https://github.com/apollographql/apollo-server/blob/master/packages/apollo-server-micro/src/ApolloServer.ts#L155 @abernix ?
PR welcome!
Most helpful comment
Just a heads up for anyone else who stumbles across this problem. Here is the code that worked for my server.
Hope it helps!