Getting an error "Error: connect ECONNREFUSED 127.0.0.1:80" while sending an image to Backblaze B2

There are a few changes I made to get this working:

  • Use bodyParser.raw() to parse the body into the Buffer format that the backblaze-b2 library is expecting. It doesn't want base64.
  • Correct uploadUrl.data.bucketId in the call to b2.uploadFile to uploadUrl.data.uploadUrl.data.uploadUrl. This is what was causing the 'connection refused' error. Since the uploadUrl wasn't a URL, I'm guessing that b2.uploadFile assumed it was a path and you wanted to connect to localhost.
  • Await the response from b2.uploadFile.
  • Use response.data rather than just response to see the API response.

I built out your code into a runnable sample:

// I like to put my env vars in a .env file
const dotenv = require('dotenv');
dotenv.config();
const B2 = require('backblaze-b2');
const fs = require('fs');

const express = require('express')
const bodyParser = require('body-parser')
const app = express()

const port = process.env.PORT || 3000

const uploadImage = async (req, res) => {
  try {
    const b2 = new B2({
      accountId: process.env.BACKBLAZE_ACCOUNT_ID,
      applicationKey: process.env.BACKBLAZE_APPLICATION_MASTER_KEY,
    });

    await b2.authorize();

    // console.log("req.body:", req.body);

    if (!req.body) return res.status(400).send('No image found!');

    const handleImage = async () => {
      try {
        let uploadUrl = await b2.getUploadUrl({
          bucketId: process.env.BACKBLAZE_BUCKET_ID,
        });

        // Make the JSON more readable
        console.log('getUploadUrl:', JSON.stringify(uploadUrl.data, undefined, 2));

        // uploadFile returns a promise, so we need to await the response
        const response = await b2.uploadFile({
          uploadUrl: uploadUrl.data.uploadUrl,
          uploadAuthToken: uploadUrl.data.authorizationToken,
          fileName: 'Pepe', //<-- TODO: Fix later
          data: req.body, // <-- This is the raw data as a buffer
          onUploadProgress: (e) => null,
        });

        const prettyResponse = JSON.stringify(response.data, undefined, 2);

        console.log('uploadFile: ', prettyResponse);
        res.send(prettyResponse);
      } catch (err) {
        console.log('Bucket error or something: ', err);
      }
    };

    handleImage();

  } catch (err) {
    console.log(err);
  }
};

app.use(bodyParser.raw({ // Raw mode returns the posted body as a Buffer
  type: '*/*' // Parse any mime type
}))

app.post('/', function (req, res) {
  uploadImage(req, res)
})

app.listen(port, () => {
  console.log(`Listening at http://localhost:${port}`)
})

Send a file with curl:

curl http://localhost:3000/ --data-binary @image.png 

Console output (somewhat redacted!):

Listening at http://localhost:3000
getUploadUrl: {
  "authorizationToken": "********",
  "bucketId": "********",
  "uploadUrl": "https://********.backblaze.com/b2api/v2/b2_upload_file/********"
}
uploadFile:  {
  "accountId": "********",
  "action": "upload",
  "bucketId": "********",
  "contentLength": 3802,
  "contentMd5": "d9b8b28f7fda3acfe7838ead41d8df38",
  "contentSha1": "f8040f1068715160ef98ab98fde80f9214cb2845",
  "contentType": "application/octet-stream",
  "fileId": "********",
  "fileInfo": {},
  "fileName": "Pepe",
  "fileRetention": {
    "isClientAuthorizedToRead": true,
    "value": {
      "mode": null,
      "retainUntilTimestamp": null
    }
  },
  "legalHold": {
    "isClientAuthorizedToRead": true,
    "value": null
  },
  "serverSideEncryption": {
    "algorithm": null,
    "mode": null
  },
  "uploadTimestamp": 1641496698000
}