在 Axios 中增加 maxContentLength 和 maxBodyLength [英] Increasing maxContentLength and maxBodyLength in Axios

查看:106
本文介绍了在 Axios 中增加 maxContentLength 和 maxBodyLength的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Axios"调用将文件信息和内容作为参数的 WCF 方法.该文件作为 base64 编码字符串被读取和发送.我的问题是,当文件大小超过某个限制时,AXIOS 会抛出异常:错误:请求正文大于 maxBodyLength 限制".我查了一下问题,发现所有解决方案都建议增加 AXIOS 配置对象中的 maxContentLength/maxBodyLength 参数,但没有成功.在 node.js 中找到以下已实现的测试用例:

I am using "Axios" to call a WCF method that takes as parameter file information and content. The file is read and sent as a base64 encoded string. My issue is that when the file size exceeds a certain limit, AXIOS throws an exception: "Error: Request body larger than maxBodyLength limit". I looked up the issue and found that all solutions suggest increasing the maxContentLength / maxBodyLength parameters in the AXIOS configuration object, but did not succeed. Find Below an implemented test case in node.js:

    var axios = require('axios');
    var fs = require('fs');
    var path = require('path')
    var util = require('util')
    let readfile = util.promisify(fs.readFile)

    async function sendData(url,data) {
        let params = data
    
        let resp = await axios({
            method: 'post',
            url: url,
            data: JSON.stringify(params),
            headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }
            // maxContentLength: 100000000,
            // maxBodyLength: 1000000000
        }).catch(err => {
            throw err;
        })
        return resp;
      }
    async function ReadFile(filepath) {
        try{
            
            let res = await readfile(filepath,'base64')
            let filename = path.basename(filepath).split('.').slice(0, -1).join('.')
            let ext = path.extname(filepath)
            
            return {data:res,fext:ext,fname:filename}
            let x = 1
        }
        catch(err)
        {
            throw err
        }
    
    }
    (async () => {
        try {
    
            let img = await ReadFile('Files/1.pdf')
            let res = await sendData('http://183.183.183.242/EMREngineEA/EMRWS.svc/web/EMR_TestUploadImg',img)
            console.log(res)
    
        }
        catch (ex) {
            console.log(ex)
        }
    }
    )();

在我的例子中,pdf 文件是 20 MB,在运行时,会抛出一个错误.错误:请求正文大于 maxBodyLength 限制"

In my case, the pdf file is 20 MB, upon running, an error is thrown. "Error: Request body larger than maxBodyLength limit"

我尝试设置 maxContentLength: 100000000, maxBodyLength: 1000000000如上所述,但没有成功.

I tried to setting the maxContentLength: 100000000, maxBodyLength: 1000000000 as presented above, but did not succeed.

感谢您的帮助.

推荐答案

在这个简单的测试中,maxBodyLength 似乎对我有用,我将数据上传到本地 Express 服务器.如果我尝试上传超过 maxBodyLength 的内容,我会收到与您相同的错误.所以我怀疑还有更多的东西,比如在你的情况下发生的重定向触发了错误.

The maxBodyLength seems to work for me in this simple test, I upload data to a local Express server. If I try to upload more than the maxBodyLength I get the same error you're getting. So I suspect there's something more, like a redirect happening in your case that's triggering the error.

为 axios 记录了一个问题 here 似乎引用了该问题,它建议将 maxContentLength 设置为 Infinity(正如其他评论者所建议的那样).

There is an issue logged for axios here that seems to reference the problem, it suggests setting maxContentLength to Infinity (as the other commenter suggests).

例如

maxContentLength: Infinity,
maxBodyLength: Infinity

测试代码如下:

const axios = require("axios");

function generateRandomData(size) {
    const a = Array.from({length: size}, (v, k) => Math.floor(Math.random()*100)); 
    return { data: a, id: 1 };
}

async function uploadData(url, size) {
    let params = generateRandomData(size);
    let stringData = JSON.stringify(params);
    console.log(`uploadData: Uploading ${stringData.length} byte(s)..`);
    let resp = await axios({
        method: 'post',
        url: url,
        data: stringData,
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        maxContentLength: 100000000,
        maxBodyLength: 1000000000
    }).catch(err => {
        throw err;
    })
    console.log("uploadData: response:", resp.data);
    return resp;
}

uploadData("http://localhost:8080/upload", 10000000);

对应的服务器代码:

const express = require("express");
const port = 8080;
const app = express();
const bodyParser = require('body-parser')

app.use(bodyParser.json({limit: '50mb'}));

app.post('/upload', (req, res, next) => {
    console.log("/upload: Received data: body length: ", req.headers['content-length']);
    res.json( { status: 'ok', bytesReceived: req.headers['content-length']});
})

app.listen(port);
console.log(`Serving at http://localhost:${port}`);

这篇关于在 Axios 中增加 maxContentLength 和 maxBodyLength的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆