H
H
hillrider2019-05-31 11:47:16
Node.js
hillrider, 2019-05-31 11:47:16

How to solve CORS blocking issue?

I am learning react/node with udemy course. Locally everything works fine, but after deployment, when trying to Login with Google, the console gives an error:
Failed to load resource: the server responded with a status of 503 (Service Unavailable)
Access to fetch at ' https://geostickers.herokuapp.com/ graphql ' from origin ' https://geoapp-pvfinzglt.now.sh ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Error logging in TypeError: Failed to fetch An
error can be generated on the client https://geoapp-pvfinzglt.now.sh
Server code:

const server = new ApolloServer({
    typeDefs,
    resolvers,
    //cors: true, - не решает проблему
    context: async ({ req }) => {
        let authToken = null;
        let currentUser = null;
        try {
            authToken = req.headers.authorization
            if(authToken) {
                currentUser = await findOrCreateUser(authToken);
            }
        } catch(err) {
            console.error(`Unable to authenticate user with token ${authToken}`)
        }
        return { currentUser }
    }
});

server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
    console.log(`Server listening on ${url}`)
});

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anatoly Chernyshev, 2019-05-31
@hillrider

https://github.com/apollographql/apollo-server/iss...
There are enough different solutions to your question in this discussion

D
Domovikx, 2020-09-24
@Domovikx

I found three solutions, but I will describe two solutions for the server side.
1. you can add a header to the response - header

(request: Request, response: Response): void => {
      response.status(200)
      response.header({
        'Access-Control-Allow-Origin': '*',
      });
}

but it is better to use the second option
2. more correct, install and use on the server -
npm i cors
https://www.npmjs.com/package/cors
add the code:
import cors from 'cors';
const server = express();
server.use(cors());

check the request, everything should work

B
Boris Cherepanov, 2019-06-22
@xakplant

There is an article " Fetch and CORS. ReactJS example "
You seem to be missing headers in the REPLY

Access-Control-Allow-Origin: https://foo.invalid // Домен с которого идут запросы
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "заголовки которые можно отправить на удалённый сервер" 
// Разрешённые методы
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question