1

I have built a microservice backend deployed on kubernetes on Digital Ocean.

I am trying to connect my react code to the backend and getting the below error:

Access to XMLHttpRequest at 'http://cultor.dev/api/users/signin' from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 
Redirect is not allowed for a preflight request.

Index.ts settings:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', '*');
  res.header('Access-Control-Request-Headers', '*');
  if (req.method === "OPTIONS") {
    res.header('Access-Control-Allow-Methods', '*');
    return res.status(200).json({});
  }
  next();
});

I would really appreciate the help. Thanks!

Karan Kumar
  • 2,678
  • 5
  • 29
  • 65
  • 1
    That last line might give you a clue on where to look. "Redirect is not allowed for a preflight request". Proxy issues or some endpoint causing a challenge? What does the signin endpoint do? – thsorens Sep 09 '20 at 21:00

2 Answers2

2

Install the cors middleware with

npm install cors

And you can use it directly like this:

const cors = require('cors');  
app.use(cors());

Or you can set specific options like this:

const cors = require('cors');    
const corsOpts = {
    origin: '*',
    credentials: true,
    methods: ['GET','POST','HEAD','PUT','PATCH','DELETE'],
    allowedHeaders: ['Content-Type'],
    exposedHeaders: ['Content-Type']
};
app.use(cors(corsOpts));

You can replace origin with your website and allowedHeaders with the headers you're going to use.

ajvg94
  • 112
  • 1
  • 7
-1

I suggest trying to use cors middleware instead of puting the headers by yourself. Maybe you're missing something. You can download cors middleware from npm and use it in your express app

const cors = require('cors')

app.use(cors())
ntoniocp
  • 34
  • 2
  • I just did. No luck. – Karan Kumar Sep 09 '20 at 21:20
  • Check this out https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSExternalRedirectNotAllowed it seems like your api its returning HTTP 302 Code (Redirection) and that's not allowed with CORS – ntoniocp Sep 09 '20 at 21:57