繁体   English   中英

无法获取:请求需要预检,不允许遵循跨源重定向

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

我正在使用Express for webserver,并使用isomorphic-fetch模块从客户端到使用XHR。

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

  • 端口3000 - >管理员网站
  • 港口3001 - >公共网站
  • 端口3002 - > API服务器

API服务器具有名为“技能”的资源,其中包含一些数据,并且如下所示:

GET http://mydomain:3002/skills

它返回JSON数据。

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

Fetch API无法加载http://example.me:3002/skills 从' http://example.me:3002/skills '重定向到' http://example.me:3002/skills/ '已被CORS政策阻止:请求需要预检,不允许遵循跨源重定向。

我不明白为什么有“重定向”或什么的。 这是我的服务器端代码,我授予了所有与CORS相关的头文件:

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服务器(实际上返回HTML)是个好主意,并希望采用这种方法。

有没有办法解决这个问题? 任何建议都会非常感激。

几年前我解决了这个问题,仍然没有理解它为什么会发生。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM