【问题标题】:Upload file with swaggerize-hapi and node.js?使用 swaggerize-hapi 和 node.js 上传文件?
【发布时间】:2017-02-11 01:15:31
【问题描述】:

我正在使用 POST 动词创建一个 API 端点,它需要一个文件。我声明我的端点如下:

    consumes:
  - application/json
  - multipart/form-data
   # format of the responses to the client (Accepts)
    produces:
    - application/json   
...
    /importfile:
        x-swagger-router-controller: import_file
        post:
          description: Sends the uploaded file to deliveries microservice to be processed.
          consumes:
            - multipart/form-data
          produces:
            - application/json
          operationId: importcsv
          parameters:
            - name: file
              in: formData
              description: file to upload
              required: true
              type: file

我在 import_file.js 中有以下内容

const util = require('util');

function importcsv(req, res) {
    console.log(req);
    const message = util.format('hi there!');
    // this sends back a JSON response which is a single string
    return res.json(message);

}

module.exports = {
    importcsv,
};

几个问题:

  1. 永远不会打印路由器控制器中的日志。这让我觉得这个函数没有被调用。怎么了?
  2. 即使返回成功响应,我也会看到:

    HTTP/1.1

    内容类型:文本/html;字符集=utf-8 缓存控制:无缓存

    多部分:未找到边界

这是为什么呢?

我是 Swagger 的新手。提前致谢。

【问题讨论】:

  • res.json 看起来不正确,您如何声明与处理程序关联的路由配置?

标签: node.js hapijs swagger-2.0


【解决方案1】:

这篇帖子here 让我觉得边界问题已经解决。好吧,它已于 2016 年 12 月 29 日修复并合并到 master 分支,但最新版本的 Swagger (see) 是在 2016 年 12 月 27 日发布的。

因此,文件上传目前无法通过 Swagger (v1.5.12) 进行。这回答了我的两个问题。

我编写了以下单元测试来测试我的控制器是否有效:

const describe = require('ava-spec').describe;
const request = require('supertest-as-promised');
const server = require('../../../../app');

describe('controllers', () => {
    describe('import_file', () => {
        describe('POST /importfile', (it) => {
            it('should accept a file parameter', async (t) => {
                const res = await request(server)
                    .post('/importfile')
                    .attach('file', 'test/data/A.csv' )
                    .expect(200);
                t.is(res.body, 'file uploaded');
            });
        });
    });
});

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多