Recently, I am doing front-end development related to GraphQL. As the back-end progress is slow, I use The Mocking Server of Apollo.
One of the problems encountered during development was that the front-end would raise an exception when accessing the Express-based GraphQL Mock Server through GraphQL. Find a relevant article on Medium and translate it for your reference.
It should be possible to determine the cross-domain cause by reporting an error.
What happened when cross-domain was not enabled to cause the above error?
In fact, CORS is actually a specification of the communication flow between the client and the server. In some cases, this process requires the server to process HTTP OPTIONS requests, as shown in the following flow chart: Cross-domain resource requests require additional OPTIONS HTTP Requests.
The problem is that express-GraphQL and Apollo-server don’t accept requests other than GET and POST, so a request failure causes an exception: OPTIONS http://localhost:4000 405 (Method not allowed).
But the problem is easy to fix. Since express-GraphQL and Apollo-Server are both express.js based. So you can fix this with Cors Middleware.
First, install cers.js
npm install cors --saveCopy the code
Then use it in server.js.
The specific code is as follows:
Request again, you can access normal:
The original link