【问题标题】:How to retrieve excel .xlsx data from Express API POST request body?如何从 Express API POST 请求正文中检索 excel .xlsx 数据?
【发布时间】:2021-02-08 20:01:51
【问题描述】:

我有一个 Angular 前端应用程序,它将 excel (.xlsx) 文件作为请求正文中的表单数据发送到我的 Express 端点。

以下是我的 Angular 服务文件中的函数:

uploadOrder(workOrder: File) {
  const formData: FormData = new FormData();
  formData.append('order', workOrder, workOrder.name);
  return this.http.post(this.uploadOrderUrl, formData);
}

下面是html表单:

<form [formGroup]="orderUploadForm" (ngSubmit)="onSubmit()">
  <input #fileUpload formControlName="orderUpload" type="file" (change)="handleOrderUpload($event.target.files)" accept=".xlsx">
  <button *ngIf="fileToUpload !== null" [disabled]="loading || (fileToUpload === null)">
    <span *ngIf="!loading">
      Upload
    </span>
  </button>
</form>

我的请求负载只是一个带有名为order 的参数的二进制文件。下面是payload来源:

------WebKitFormBoundary6kTGShrkCmA5pcA4
Content-Disposition: form-data; name="order"; filename="sample-order.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet


------WebKitFormBoundary6kTGShrkCmA5pcA4--

我的 Express 中间件,用 typescript 编写,配置如下:

// src/config/app.ts

private config(): void {
  this.app.use(bodyParser.json());
  this.app.use(bodyParser.urlencoded({ extended: true }));
}

而端点是这样写的:

app.post('/api/submit-excel', (req: Request, res: Response) => {
  console.log(req.body.order); // <-- req.body.order is returning undefined

  convertExcelToJson(req.body.order); 
  res.status(200).json({ message: "Post request successfull" });
});

我的req.body.order 正在返回undefined

我的应用配置文件中是否缺少任何内容,这就是它无法从请求正文中获取数据的原因?非常感谢任何指导或帮助,谢谢。

编辑:

尝试使用express-fileupload,但看到以下错误:

Error: Cannot find module 'express-fileupload'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (C:\Users\username\Software\Workspace\express-app\dist\config\app.js:5:20)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

我已经安装了依赖 npm i @types/express-fileupload 并从 /node_modules/@types/express-fileupload/index 导入了 import * as fileUpload from 'express-fileupload'; 中的 import * as fileUpload from 'express-fileupload';,但它仍然没有工作。

【问题讨论】:

    标签: node.js angular typescript api express


    【解决方案1】:

    您可以使用express-fileupload

    // src/config/app.ts
    
    private config(): void {
      this.app.use(bodyParser.json());
      this.app.use(bodyParser.urlencoded({ extended: true }));
      // Enable files upload. Don´t forget to import the package
      this.app.use(fileUpload({
        createParentPath: true
      }));
    }
    
    async app.post('/api/submit-excel', (req: Request, res: Response) => {
      try {
        if(!req.files) {
          res.send({
            status: false,
            message: 'No file uploaded'
          });
        } else {
          const order = req.files.order;
    
          // Process your file
          convertExcelToJson(order); 
          
          // You can also use the mv() method to place the file in a upload directory (i.e. 'uploads')
          order.mv('./uploads/' + order.name);
    
          // Send response
          res.status(200).json({message: 'Post request successfull'});
        }
      } catch (err) {
        res.status(500).send(err);
      }
    });
    

    【讨论】:

    • Error: Cannot find module 'express-fileupload',我看到了这个错误。我已经安装了依赖项npm i @types/express-fileupload 并将它导入到我的config/app.ts 中的import * as fileUpload from 'express-fileupload'; /node_modules/@types/express-fileupload/index。我错过了什么吗?
    • 请记住,npm i @types/express-fileupload 只安装 TS 的类型,而不是包本身。你必须运行npm i express-fileupload
    猜你喜欢
    • 2021-07-21
    • 2014-05-18
    • 2019-07-15
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 2019-06-26
    相关资源
    最近更新 更多