获取失败:请求需要预检,不允许遵循 cross-origin 重定向

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

我正在为网络服务器使用 Express,并使用 isomorphic-fetch 从客户端到使用 XHR 的模块。

我的 Web 应用程序有三个服务器:

API 服务器有名为 "skills" 的资源,其中有一些数据,可以这样获取:

GET http://mydomain:3002/skills

它returnsJSON数据。

但是当我从 3000/3001 请求 3002 时,它失败并显示以下消息:

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.

我不明白为什么会有 'redirection' 之类的东西。这是我的服务器端代码,我授予所有 CORS 相关 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..."));

这是使用 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'
})...

如您所见,没有重定向代码。我花了将近一天的时间来解决这个问题,但是我尝试的一切都失败了,我找到的所有信息都是无用的。

我认为将服务拆分到 API 服务器和 Web 服务器(实际上是 returns HTML)是个好主意,我想采用这种方法。

有办法解决这个问题吗?任何建议将不胜感激。

我几年前就解决了这个问题,仍然不明白为什么会这样。

但是我的解决方案很简单,将每个 API 放入 /api 路径。