被 CORS 策略阻止的 React-S3

Posted

技术标签:

【中文标题】被 CORS 策略阻止的 React-S3【英文标题】:React-S3 blocked by CORS policy 【发布时间】:2020-07-03 04:23:37 【问题描述】:

所以我使用React-S3 将文件从我的反应应用程序上传到 S3 存储桶。我正在使用代理服务器,但仍然给我以下错误

Access to fetch at 'https://atlantic-files.s3.amazonaws.com/' from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

这是我的服务器

const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const app = express();

app.use(express.static(path.join(__dirname, 'build')));
app.use(express.urlencoded( extended: true ));
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: false ));

app.use((req, res, next) => 
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', "GET,PUT,POST,DELETE");
    res.header('Access-Control-Allow-Methods', "Content-Type");
    next();
);

app.get('/*', function (req, res) 
    res.sendFile(path.join(__dirname, 'build/index.html'), function (err) 
        if (err) 
            res.status(500).send(err)
        
    )
)

app.get('/', function (req, res) 
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
);

app.listen(5000);


console.log('App is listening on port 5000');

有什么办法吗?

【问题讨论】:

【参考方案1】:

在要启用 cors 的路由上尝试 cors。 https://expressjs.com/en/resources/middleware/cors.html

const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const cors = require('cors');
const app = express();

app.use(express.static(path.join(__dirname, 'build')));
app.use(express.urlencoded( extended: true ));
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: false ));

app.use((req, res, next) => 
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', "GET,PUT,POST,DELETE");
    res.header('Access-Control-Allow-Methods', "Content-Type");
    next();
);

app.get('/*',function (req, res) 
    res.sendFile(path.join(__dirname, 'build/index.html'), function (err) 
        if (err) 
            res.status(500).send(err)
        
    )
)

app.get('/', cors(), function (req, res) 
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
);

app.listen(5000);


console.log('App is listening on port 5000');

【讨论】:

@MarkusHayner,对不起,我把 cors 放在了错误的路线中间。我已经编辑过了。立即尝试

以上是关于被 CORS 策略阻止的 React-S3的主要内容,如果未能解决你的问题,请参考以下文章

访问被 CORS 策略阻止:没有“访问控制允许来源”

AWS API 调用被 CORS 策略阻止

请求被 CORS 策略阻止

Angular AWS 被 CORS 策略阻止

quarkus:被 CORS 策略阻止

http 请求被 Flutter Web 的 Cors 策略阻止