简体   繁体   中英

Node - POST local file to remote endpoint using AXIOS

I'm having a bit of trouble taking a local file on the NodeJS server and uploading it to a web endpoint. I keep getting error:

AxiosError: Request failed with status code 400 at settle (D:\myproject\node_modules\axios\dist\node\axios.cjs:1855:12) at IncomingMessage.handleStreamEnd (D:\myproject\node_modules\axios\dist\node\axios.cjs:2712:11) at IncomingMessage.emit (node:events:539:35) at endReadableNT (node:internal/streams/readable:1345:12) at processTicksAndRejections (node:internal/process/task_queues:83:21) { code: 'ERR_BAD_REQUEST',

I'm not entirely sure what I'm doing wrong. I've poured over a lot of posts and seem to be structuring my AXIOS post request correctly?

try {
    const fileStream = await fs.createReadStream('./pathtofile.ext');
    let formData = new FormData();
    formData.append('myFile', fileStream, 'pathtofile.ext');
    axios.post('https://my.endpoint.com', formData, {
            headers: {
                ...formData.getHeaders(),
            }
        })
        .then(res => res.data)
        .catch( err => console.log(err))
} catch(err) {
    console.error(err)
}

I'm at a bit of a loss, as I can't seem to figure out what I'm doing wrong with such a simple task? The headers also appear to be correct when I call "getHeaders()", it's showing " 'content-type': 'multipart/form-data; "

I appreciate any and all assistance!

I'm not sure why you're trying to read the file with a ReadStream, since you need the whole file to post it to your endpoint.

The benefits of using a ReadStream is to perform operations as you read the file. So with every chunk of the file you do something.

In this case, i believe all you need to do is just read the file and then firing your POST request.

You can do this by using readFileSync instead of createReadStream .

Your code should maybe go on this direction:

try {
    const fileContents = await fs.readFileSync('./pathtofile.ext',{encoding: 'the-right-encoding'});
    let formData = new FormData();

    formData.append('myFile', fileContents, 'pathtofile.ext');
    axios.post('https://my.endpoint.com', formData, {
        headers: {
            ...formData.getHeaders(),
        }
    })
    .then(res => res.data)
    .catch( err => console.log(err));
} catch(err) {
    console.error(err)
}

That way, the await keyword would have more sense, since you'll be waiting for the readFileSync promise to resolve.

Be sure to choose the right encoding for reading the file.

Also, since you're using Axios, you can check for the status of the upload by providing a callback function to the post method.

const onUploadProgress = (event) => {
    const percentage = Math.round((100 * event.loaded) / event.total);
    console.log(percentage);
  };

Usage: https://www.bezkoder.com/axios-file-upload/

Firstly, you should go to a site like Reqbin and simulate the request to ensure your web endpoint is not the issue. I took the trouble to test your code with my own endpoint and it works perfectly. Most of the time, such issues are due to Authorization, Rate-limiting or something of that sort. Perhaps I could help out if I knew the kind of endpoint. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM