LoginSignup
1

More than 3 years have passed since last update.

posted at

updated at

Organization

Firebase FunctionsのApolloServerがCORSに阻まれ動かない

以前書いたFirebase FunctionsでGraphQLを使う、その後困ったことです。

まとめ

NuxtのApolloClientからFunctionsのGraphQL呼ぶとCORSでエラーになりました。
createHandlerの引数にcorsオプションを渡してやるとスッキリします。

// 略

const server = new ApolloServer({ typeDefs, resolvers });

exports.graphql = functions.https.onRequest(server.createHandler({
  cors: {
    origin: 'http://localhost:3000', // 許可するオリジン
    credentials: true
  }
}));

補足

CORSとは https://developer.mozilla.org/ja/docs/Web/HTTP/CORS
オリジンって https://developer.mozilla.org/ja/docs/Glossary/Origin
僕はlocalhost:3000のnuxtからlocalhost:5001のfunctionsに投げてたので一生怒られてました。
動作確認ができないので詰みです。
サーバからレスポンス返すときのヘッダにAccess-Control-Allow-Originを入れてやればOKです。
今回のApolloServerではこの辺で設定してる感じです。配列にすれば複数許可できるんですね。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
1