4

I am using an existing API call to send a file to our cloud provider via Nodejs. I have seen several different methods of doing this online, but figured I would stick to using "fetch" as most of my other API calls have been using this as well. Presently, I keep getting 500 internal server error and am not sure why? My best conclusion is that I am not sending the file properly or one of my pieces of formdata are not resolving correctly. See the below code:

const fetch = require("node-fetch");
const formData = require("form-data");
const fs = require("fs");
var filePath = "PATH TO MY FILE ON SERVER WITH FILE NAME";

var accessToken = "Bearer <ACCESS TOKEN>;
var url = '<API URL TO CLOUD PROVIDER>';
var headers = {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json',
    'Authorization': accessToken
};
const form = new formData();
const buffer = fs.readFileSync(filePath);
const apiName = "MY_FILE_NAME";

form.append("Content-Type", "application/octect-stream");
form.append("file", filePath);

console.log(form);

fetch(url, { method: 'POST', headers: headers, body: form })
    .then(response => response.json())
    .then(data => {
        console.log(data)
    })
    .catch(err => {
        console.log(err)
    });

This my first time attempting something like this so I am next to certain I am missing something. Any help with getting me in the right direction is appreciated.

4
  • at what line it is giving error? Commented Mar 10, 2020 at 14:56
  • It throws error on the back-end presumably because I am not sending something to the server properly. I do not have a way to look at how the script is sending the request, i.e. logging to show the outbound POST to the back-end. Without that I am guessing on what could be the issue. What would be nice is to have something that would show the actual fetch in logging as it will appear to the back-end server. This way I can tell what is not being sent properly as I do have this working in postman and in curl so it would be an easy comparison. Commented Mar 10, 2020 at 15:07
  • APIs can be implemented in a variety of different ways. I would posit that it'd be nearly impossible for anyone in the SO community to be able to definitively point to why a specific API endpoint would throw a 500 Internal Server Error without more information or documentation. After exhausting all local debugging options for your request, the next step should generally be to contact whichever team supports the API you're attempting to communicate with for assistance. Commented Mar 10, 2020 at 15:09
  • So the I found what the issue is by using an NodeJS express echo server. The problem is that the above script doesn't actually upload the file with the fetch call. I will continue troubleshooting and hopefully post the correct fetch code soon..... Commented Mar 10, 2020 at 17:05

2 Answers 2

4

So the issue was exactly what I mentioned above. The code was not uploading the file I specified. I finally figured out why and below is the modified code which will grab the file and upload to our cloud service provide:

const fetch = require("node-fetch");
const formData = require("form-data");
const fs = require("fs");
var apiName = process.env['API_PATH'];
var accessToken = "Bearer" +" "+ process.env['BEARER_TOKEN'];
var url = process.env['apiEnv'] +"/" +"archive";
var headers = {
    'Accept': 'application/json',
    'Authorization': accessToken,
};
const form = new formData();
const buffer = fs.readFileSync(apiName);


const uploadAPI = function uploadAPI() {
    form.append("Content-Type", "application/octet-stream");
    form.append('file', buffer);

    fetch(url, {method: 'POST', headers: headers, body: form})
        .then(data => {
            console.log(data)
        })
        .catch(err => {
            console.log(err)
        });
};

uploadAPI();

Being new to Javascript/Nodejs I wasn't really sure what the "buffer" variable did. After finally figuring it out I realized I was adding too many body form params to the request and the file was not being picked up and sent to the provider. All code above is using custom variables, but if for whatever reason someone wants to use it, then simply replace the custom variables with your own....Thanks again for any and all assistance....

Sign up to request clarification or add additional context in comments.

2 Comments

You had a typo in your Content-Type header. I've fixed it, but you may want to check your code!
What is form.append("Content-Type", "application/octet-stream"); for? Content-type is a header, not a form field.
-2
import fs from 'fs'
import FormData from 'FormData';

const fileStream = fs.createReadStream('./file.zip');
const form = new FormData();

form.append('key', fileStream, 'file.zip');

const response = await axios.post(url, form, {
    headers: {
        ...form.getHeaders(),
    },
});

2 Comments

Welcome to SO! Please don't post code-only answers but add a little textual explanation about how and why your approach works and what makes it different from the other answer given. You can find out more at our "How to write a good answer" page.
The question asks for a fetch() solution, not Axios.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.