LoginSignup
1
0

More than 5 years have passed since last update.

ローカル開発環境でApollo ClientからMicroへ通信するときのCORS設定

Posted at

はじめに

node.js によるGraphQLサーバーを実装している時にCORS関係のエラーで嵌ったので共有しておきます。
尚、CORSについては既にいろいろな方が解説されているので説明は省きます。

前提

  • サーバー側: Micro: v9.3.3
  • クライアント側: Apollo Client: v2.4.8
  • サーバー, クライアント共にローカル開発環境で動いている

症状

ローカル開発環境で、GraphQL Playground では動作確認できるのに Apollo Client から正しいGraphQLクエリを投げているのにも関わらず Error: "Network error: NetworkError when attempting to fetch resource." が出る。

原因 & 解決策

CORS の仕様で単純リクエストでないリクエストの時に発生する preflight request にサーバー側が対応できていなかったので対応できるようにする。

preflight request とは

この記事 などで詳しく解説されているので参考にしてください。要は CORS 時に発生することのある OPTION リクエストのことらしいです。 今回の場合は micro-cors によってレスポンスヘッダが適切に設定されているので 200 を返すだけで大丈夫です。

micro-cors を使用しています。

import { send } from 'micro'
import { get, post, router, options } from 'microrouter'
import { ApolloServer } from 'apollo-server-micro'
import { schema } from './schema'

const apolloServer = new ApolloServer({ schema })
const graphqlPath = '/graphql'
const graphqlHandler = apolloServer.createHandler({ path: graphqlPath })

module.exports = cors({
  allowMethods: ['GET', 'POST']
})(
  router(
    post(graphqlPath, graphqlHandler),
    get(graphqlPath, graphqlHandler),
    // to respond with a preflight request
    options(graphqlPath, (_, res) => send(res, 200)),
    (_, res) => send(res, 404, 'Not Found'),
  )
)

若干説明不足な感じもしますが問題解決の一助となれば幸いです。

参考

1
0
0

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
  3. You can use dark theme
What you can do with signing up
1
0