0

I built a program where a user can send request with a PDF URL then sever download it and forward into an external API endpoint. Now, the code able to download file but it hit this error when it start to read the file.

I must admit that Promises is something I hate to learn hence I used Async Function with Awaits and in other cases I used normal functions. Promises is so hard to grasp. The syntax make it hard to read.

Code is below:

const fs = require('fs');
const url = require("url");
const path = require("path");
const http = require('http')
const rp = require('request-promise');
const app = express();
const port = 8999;


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/upload-invoice', (req, res) => {
  
  var parsed = url.parse(req.body.FileURL);
  var filename = (path.basename(parsed.pathname));
  var downloaded_file_path = `invoices/${filename}`;
  
  function download() {
    
    var options = {
      hostname: parsed.hostname,
      port: 2799,
      path: parsed.path,
      method: 'GET'
    }
    
    const file = fs.createWriteStream(`invoices/${filename}`);
    
    const make_request = http.request(options, (response) => {
      response.pipe(file);
    });
    
    make_request.end();
    
    try {
      setTimeout(function () {
        upload()
      }, 1000);
    } catch (error) {
      console.log('An Error occured when uploading file,'+error);
    }
    
  }
  
  async function upload() {
    
    const flow = "Upload Invoice"
    var file_stream = fs.createReadStream(downloaded_file_path)
    
    var options = {
      method: 'POST',
      strictSSL: true,
      uri: 'https://endpoint.goes.here',
      formData: {
        'file': file_stream
      },
      headers: {
        'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryzte28ISYHOkrmyQT'
      },
      json: req.body,
      resolveWithFullResponse: true
    }
    
    try {
      var response = await rp(options)
      res.send(response.body)
    }
    catch (error) {
      console.log(`An error on ${flow} flow for unknown user. Here is more info about error,
        ${error}
        `)
        res.send("Error")
      }
    }
    
    download()
  });
  
  app.listen(port)

Update:

      formData: {
        name: filename,
        file: {
          value: fs.createReadStream(downloaded_file_path),
          options: {
            filename: filename,
            contentType: 'application/pdf'
          }
        }
      }

I've tried this code too but it output same error.

1 Answers1

0

It works after removing json: req.body

My fault.