上传图片时错误 413 payload too large

Error 413 payload too large when upload image

我正在尝试通过使用 base64 进行图像检测从本地上传图像。
在 localhost 和 postman 中一切正常。
但是在部署之后,我得到了 CROS 错误。

我已经在 server.js

中获得了 cors 中间件
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 }));

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

No 'Access-Control-Allow-Origin' header is present on the requested resource.

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

  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'
        })

然后显示413 payload too large

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

  1. CORS 预检

server.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));

显示错误:

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'
  1. 我删除credentials: 'include'后,它又显示413 payload too large

我很困惑...有人知道如何解决吗?谢谢。

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

像这样:

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

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

对于下一位需要更多详细信息的人: Error: request entity too large
对于需要设置 Nginx 配置文件的人: Increasing client_max_body_size in Nginx conf on AWS Elastic Beanstalk

快速使用

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

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

client_max_body_size 50M;

然后用sudo service nginx restart

重启Nginx
This solution is for ANDROID 

In my case @Headers("Content-Type: application/json") is used extra which is not needed.

@Multipart

@POST("user-management/user/profile")
@Headers("Content-Type: application/json")
fun updateProfileImage( @Part file: MultipartBody.Part,@Header("Authorization") authKey: String): Call<ProfileImageResponse>

我已经删除了 header @Headers("Content-Type: application/json") 由于我正在使用多部分,所以不要在 header.

以上使用

删除 Header 代码后成功执行。

@Multipart
@POST("user-management/user/profile")
fun updateProfileImage( @Part file: MultipartBody.Part,@Header("Authorization") authKey: String):Call<ProfileImageResponse>