Failed to fetch: Request requires preflight, which is disallowed to follow cross-origin redirect

1.7k views Asked by At

I'm using Express for webserver, and using isomorphic-fetch module from client to using XHR.

I have three servers for my web application:

  • Port 3000 -> Admin Website
  • Port 3001 -> Public Website
  • Port 3002 -> API Server

API Server has resources named "skills" which has some data, and get it like this:

GET http://mydomain:3002/skills

it returns JSON data.

But when I request to 3002 from 3000/3001, it fails with this message:

Fetch API cannot load http://example.me:3002/skills. Redirect from 'http://example.me:3002/skills' to 'http://example.me:3002/skills/' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

I don't get it why there is 'redirection' or something. This is my server side code, I granted all CORS related headers:

const express = require('express');
const app = express();

...

// CORS
app.use((req, res, next) => {
    var allowedOrigins = ['http://example.me', 'http://example.me:3000', 'http://example.me:3001', 'http://example.me:3002'];
    var origin = req.headers.origin;

    if(allowedOrigins.indexOf(origin) > -1){
        res.setHeader('Access-Control-Allow-Origin', origin);
    }

    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');

    if (req.method === "OPTIONS") {
        return res.status(200).end();
    }

    next();
});

app.use(require('./routes'));

...

app.listen(3002, () => console.log(".API Server listening on port 3002..."));

And this is client side code that using Fetch API:

fetch('http://example.com:3002/skills', {
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    credentials: 'include',
    cache: 'no-store',
    mode: 'cors'
})...

As you can see there is no redirection code. I spent almost a day to fix this issue, but everything I tried was all failed, every information that I found was useless.

I think splitting services to API Server and Web Server(actually returns HTML) was good idea, and want to go with this approach.

Is there a way to fix this problem? Any advice will very appreciate.

1

There are 1 answers

0
modernator On BEST ANSWER

I solved this issue few years ago, still don't get it why it happened.

However my solution was simple, put every API into /api path.