上传图片时出现错误 413 负载过大

use*_*792 3 javascript node.js reactjs http-status-code-413

我正在尝试通过使用base64进行图像检测从本地上传图像。
在本地主机和邮递员中一切正常。
但是在部署后,我收到了 CROS 错误。

我已经有了 cors 中间件 server.js

const express = require("express");    
const cors = require("cors");
const bodyParser = require("body-parser");

const app = express();

app.use(cors());

app.use(bodyParser.json({ limit: "10000kb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "10000kb", extended: true }));
Run Code Online (Sandbox Code Playgroud)

cors 中间件在使用 url 获取图像时工作正常,
但是当我尝试使用base64从本地上传图像时,控制台显示:

No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的解决方案:

  1. cors-anywhere
App.js

    const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
    
    fetch(proxyUrl + API_CALL.IMAGE_URL, {
          method: 'post',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            inputLink: inputLink,
            inputMethod: inputMethod
          }),
          credentials: 'include'
        })
Run Code Online (Sandbox Code Playgroud)

然后显示413 payload too large.

由于在localhost和postman中测试都没有错误,我发现有些文章说可能仍然是cors错误。

  1. CORS 预检

服务器.js

    const corsOptions = {
        origin: 'https://front-end-url/',
        methods: 'GET, POST, PUT',
        credentials: true,
        allowedHeaders: 'Content-Type,Authorization',
        exposedHeaders: 'Content-Range,X-Content- Range'
    };
    app.options('/imageUrl', cors(corsOptions));
Run Code Online (Sandbox Code Playgroud)

它显示错误:

CORS policy: Response to preflight request doesn't pass access control check: 
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' 
when the request's credentials mode is 'include'
Run Code Online (Sandbox Code Playgroud)
  1. 删除后credentials: 'include',它413 payload too large再次显示。

我很困惑......有谁知道如何解决它?谢谢你。

use*_*792 10

最后通过放置express.json() AFTER 来 修复错误 bodyParser

像这样:

app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(express.json());
Run Code Online (Sandbox Code Playgroud)

如果先运行 express.json(),express 会将全局限制设置为 1mb。

对于下一个需要更多细节的人: 错误:请求实体太大
而对于需要设置 Nginx 配置文件的人: 在 AWS Elastic Beanstalk 上的 Nginx conf 中增加 client_max_body_size


Joã*_*ira 6

在快速使用中

app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000 }))
Run Code Online (Sandbox Code Playgroud)

但在 Nginx 中,您还必须/etc/nginx/nginx.conf在块内编辑并添加以下行http

client_max_body_size 50M;
Run Code Online (Sandbox Code Playgroud)

然后重新启动 Nginxsudo service nginx restart