skip to Main Content

I have set up my server as below, specifying the origin as the netlify adddress of our react app. but we still get cors errors. Access to fetch at ‘https://lendify-production.up.railway.app/collection/all’ from origin ‘https://grand-tapioca-07d51d.netlify.app’ 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.

    import Koa from 'koa';
    import parser from 'koa-bodyparser';
    import cors from 'koa-cors';
    import proxy from 'koa-proxies';
    import { Server } from 'socket.io';
    import http from 'http';
    import dotenv from 'dotenv';
    import router from './router';
    import connectDb from './models/_index';
    import { ioConnect } from './controllers/socketHandler.controller';

    dotenv.config();
    const PORT = process.env.PORT || 5001;
    const app = new Koa();

    app.use(cors({
      origin: process.env.CLIENT_URL,
      methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
      headers: ['Origin', 'Content-Type', 'Accept', 'Authorization'],
      credentials: true,
    }));
    
    
    app.use(parser());
    app.use(router.routes());
    app.use(router.allowedMethods());

We are able to login but with every other route i get a cors error. I have taken out the authentication and I have tried setting up a proxy but plays havoc with the socket.io we have set up. the headers are somehow not set up correctly with the cors.

2

Answers


  1. You need to set the Access-Control-Allow-Origin header on your server to the same value as the Origin from which the request originates. This way, when the browser executes the preflight request, your server will return this header in the response, allowing your Origin to access the requested resource.

    Login or Signup to reply.
  2. If you call an API from one origin to different origin, the browsers bloack them. You need to allow Cross Origin access for specific origin like shown below

    app.use(cors({
          origin: ['https://google.com/','https://facebook.com','http://localhost:3000']
    }));
    
    

    or allow all origins like

    app.use(cors({
          origin: "*"
    }));
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search