request / request-promise

The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.
ISC License
4.77k stars 297 forks source link

Write After End Error When Sending File using Request Promise #344

Closed gerald-dotcom closed 4 years ago

gerald-dotcom commented 4 years ago

I posted same question on stackoverflow but there are no answers why is this happening with your library.

I thought it would best to write about this by raising issue on this repo.

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.

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

I also tried an another code but it too not working:

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

gerald-dotcom commented 4 years ago

It working after removing json: req.body

My fault.