使用nodejs和react上传文件时“被CORS策略阻止:请求的资源上不存在‘Access-Control-Allow-Origin’标头”

问题描述 投票:0回答:1

[在此处输入图像描述][1]每次我尝试将文件从reactjs发送到nodejs时,cors都会出现错误“No 'Access-Control-Allow-Origin'”。我已经添加了所有标题。除了文件上传之外的所有其他请求都可以正常工作,但有点慢,我不知道为什么。 另一个请求是将文件从nodejs发送到reactjs,并且运行缓慢。 我使用 aws Lightsail Bitnami 服务器,我尝试更改所有配置,但没有任何改变。

那么我该如何解决它?

这是我添加的标题

app.use((request, response, next) => {
  response.header("Access-Control-Allow-Origin", "*");
  response.header("Access-Control-Allow-Credentials", "true");

  response.header(
    "Access-Control-Allow-Methods",
    "GET,POST,DELETE,PUT,OPTIONS"
  );
  response.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );

  next();
  console.log("did i passed it ?");
});
app.use(express.static("public"));

我也使用了 cors 包,但它也不起作用

const app = express();
app.use(bodyParser.json());
//app.options("*", cors());
app.use(cors())

提前致谢,

我尝试添加标头,尝试使用 cors 包并更改了 bitnami 配置

这是我的 bitnami 主机配置:

<VirtualHost *:443>
ServerName timesheet.3f.com
SSLEngine on
SSLCertificateFile "/opt/bitnami/apache/conf/timesheet.3f.com.crt"
SSLCertificateKeyFile "/opt/bitnami/apache/conf/timesheet.3f.com.key"
</VirtualHost>

<VirtualHost *:443>
  ServerName timeapp.3f.com
  SSLEngine on
  ProxyPass / http://localhost:3004/
  ProxyPassReverse / http://localhost:3004/
  SSLCertificateFile "/opt/bitnami/apache/conf/timeapp.3f.com.crt"
  SSLCertificateKeyFile "/opt/bitnami/apache /conf/timeapp.3f.com.key"
</VirtualHost>

这是从nodejs和reactjs发送的标头。因此所有标头都包含在内,但 cors 仍然出现相同的错误。 [1]:https://i.stack.imgur.com/x9vXB.png

node.js reactjs express bitnami amazon-lightsail
1个回答
0
投票

我认为你实例化了错误/错误的地方。试试这个:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

// And here the rest of your app
© www.soinside.com 2019 - 2024. All rights reserved.