Increasing maxContentLength and maxBodyLength in Axios

后端 未结 1 943
一生所求
一生所求 2021-01-20 04:29

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

1条回答
  •  粉色の甜心
    2021-01-20 05:08

    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.

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

    e.g.

    maxContentLength: Infinity,
    maxBodyLength: Infinity
    

    Test code below:

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

    Corresponding server code:

    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}`);
    

    0 讨论(0)
提交回复
热议问题