title: Could not get binary data in ASP.NET Core 3 from HTML/JS client through nodejs express
body: <p>I have <strong>HTML/JS client</strong> side that communicate with <strong>nodejs/express server</strong> side. The client sends file to the node server - everything works fine so far.
  The node server calls https.request to send the binary data to a<strong>nother ASP.NET Core 3 component</strong> (server).
  The issue is that the ASP.NET Core 3.1 controller keep getting errors/empty data.
  The API: TransferModel from the controller.cs either get empty data array or throws exceptions (depends ont the changes i am doing in the nodejs)</p>
  
  <h2>Client/HTML Side</h2>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;label style="font-weight: bold;"&gt;Upload Model File...&lt;/label&gt;
      &lt;form action="fileupload" method="post" enctype="multipart/form-data"&gt;
        &lt;input type="file" name="filetoupload"&gt;&lt;br&gt;
        &lt;br&gt;&lt;input class="button" type="submit"&gt;
      &lt;/form&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <h2>Node JS Sever - partial</h2>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express');
  const path = require('path');
  var bodyParser = require("body-parser");
  const plantAPI = require('./plantSimAPI')
  var formidable = require('formidable');
  
  var app = express();
  app.use(bodyParser.urlencoded({ extended: false }))
  app.use(bodyParser.json())
  
  var serverUrl = 'localhost'
  var port = '5000'
  
  app.post('/fileupload', (req, res) =&gt; {
    var form = new formidable.IncomingForm();
    form.keepExtensions = true;
    form.onPart = function (part) {
      if (!part.filename) {
        // let formidable handle all non-file parts
        form.handlePart(part);
        return;
      }
      part.on('data', function (data) {
        transferModel(data);    
      });
      part.on('end', function () {
        transferModel([]);
        res.send(200);
      });
      part.on('error', function (err) {
        // handle this too
        res.json(err);
      });
    }
  
    form.parse(req, function (err, fields, files) {
      //pass the file to the plant sim server
      // plantSim.
        //res.send(200);
        console.log('ahmad');
    });
  });
  
  
      function transferModel(data, ondone) {
          this.callPlantSimAPI2('/plantsim/api/model/transfer', 'PUT', data, () =&gt; {
              if (ondone) ondone();
          });
  
      }
      
      function callPlantSimAPI2(path, method, data, onDone) {
          const options = {
              host: serverUrl,
              port: port,
              path: path,
              method: method,
              agent: new https.Agent({
                  rejectUnauthorized: false,
              }),
              headers: {
                  "Content-Type": "multipart/form-data" //"application/octet-stream"
              }
          };
  
          var req = https.request(options, function (res) {
              console.log('STATUS: ' + res.statusCode);
              console.log('HEADERS: ' + JSON.stringify(res.headers));
              res.setEncoding('utf8');
              res.on('data', function (chunk) {
                  console.log('BODY: ' + path + ' : ' + chunk);
                  if (onDone) onDone(chunk);
              });
              res.on('error', (err) =&gt; {
                  if (onDone) onDone("")
              });
              res.on('end', () =&gt; {
                  if (onDone) onDone("")
              })
          });
  
          req.on('error', function (e) {
              console.log('problem with request: ' + e.message);
              if (onDone) onDone("");
          });
  
          // write data to request body
          if(data &amp;&amp; data.length&gt;0) req.write(data);
          req.end();
      }</code></pre>
  </div>
  </div>
  </p>
  
  <h2>ASP.NET Web API Core3.1</h2>
  
  <h1>Startup.cs</h1>
  
  <pre><code> public void ConfigureServices(IServiceCollection services)
          {
              services.AddCors();
              services.AddControllers();
          }
  
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
  
              app.UseHttpsRedirection();
              //first routing
              app.UseRouting();
              //then
              app.UseCors(
                  options =&gt; options.SetIsOriginAllowed(x =&gt; _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
              );
              app.UseAuthorization();
  
              app.UseEndpoints(endpoints =&gt;
              {
                  endpoints.MapControllers();
              });
  
          }
  </code></pre>
  
  <h1>Controller.cs</h1>
  
  <pre><code>namespace PlantSimAPI.Controllers
  {
      [ApiController]
      [EnableCors("simapi")]
      [Route("plantsim/api")]
      public class PlantSimAPIController : ControllerBase
      {
          [HttpPut]
          [Route("model/transfer")]
          public async Task&lt;IActionResult&gt; TransferModel( [FromBody]byte[] data)
          {
               try
                  {
                      //byte[] data = { };
                      using (var ms = new MemoryStream(1024*8))
                      {
                          await Request.Body.CopyToAsync(ms);
                          data = ms.ToArray();
                          //do something with my data
                      }
                      return Ok();
                  }
                  catch (Exception ex)
                  {
                      //Log message
                      this._logger.LogError(ex.Message);
                      //return bad result
                      return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
                  }
          }
      }
  }
  </code></pre>