首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >格式化模式验证多部分/表单数据(正文应为object)

格式化模式验证多部分/表单数据(正文应为object)
EN

Stack Overflow用户
提问于 2020-02-14 14:20:18
回答 1查看 3.8K关注 0票数 0

多部分格式的数据文件上传时间错误主体应该是对象,而且我也在使用ajv插件,我仍然在使用同样的问题。下面是我的参考代码。

app.js

代码语言:javascript
运行
复制
const fastify = require('fastify')({
    logger: true
});

const Ajv = require('ajv');
const ajv = new Ajv({
    useDefaults: true,
    coerceTypes: true,
    $data: true,
    extendRefs: true
});

ajv.addKeyword("isFileType", {
    compile: (schema, parent, it) => {
        parent.type = "file";
        delete parent.isFileType;
        return () => true;
    },
});

fastify.setSchemaCompiler((schema) => ajv.compile(schema));

routes.js

代码语言:javascript
运行
复制
schema: {
    tags: [{
        name: 'Category'
    }],
    description: 'Post category data',
    consumes: ['multipart/form-data'],
    body: {
        type: 'object',
        isFileType: true,
        properties: {
            name: {
                type: 'string'
            },
            thumb_url: {
                isFileType: true,
                type: 'object'
            },
            img_url: {
                isFileType: true,
                type: 'object'
            },
            status: {
                type: 'number',
                enum: [0, 1],
                default: 1
            }
        },
        required: ['name', 'thumb_url', 'img_url']
    },
    response: {
        201: {
            type: 'object',
            properties: categoryProperties
        }
    }
}

响应

代码语言:javascript
运行
复制
{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "body should be object"
}

我怀疑错误出在我发送数据的方式上,但我很难弄清楚这一点。我读到过这个错误,它似乎是在将一个对象传递给formData时生成的,但我发送的是一个字符串,所以我不明白为什么会发生这种情况。提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2020-02-14 15:43:04

我认为你管理multipart的配置是错误的,模式应该按照这个工作示例进行修复:

代码语言:javascript
运行
复制
const fastify = require('fastify')({ logger: true })

fastify.register(require('fastify-multipart'), {
  addToBody: true
})

const Ajv = require('ajv')
const ajv = new Ajv({
  useDefaults: true,
  coerceTypes: true,
  $data: true,
  extendRefs: true
})

ajv.addKeyword('isFileType', {
  compile: (schema, parent, it) => {
    parent.type = 'file'
    delete parent.isFileType
    return () => true
  }
})

fastify.setSchemaCompiler((schema) => ajv.compile(schema))

fastify.post('/', {
  schema: {
    tags: [{
      name: 'Category'
    }],
    description: 'Post category data',
    consumes: ['multipart/form-data'],
    body: {
      type: 'object',
      properties: {
        name: { type: 'string' },
        thumb_url: { isFileType: true },
        img_url: { isFileType: true },
        status: {
          type: 'number',
          enum: [0, 1],
          default: 1
        }
      },
      required: ['name', 'thumb_url', 'img_url']
    }
  }
}, async (req, reply) => {
  let filepath = path.join(__dirname, `${req.body.thumb_url[0].filename}-${Date.now()}`)
  await fs.writeFile(filepath, (req.body.thumb_url[0].data))

  filepath = path.join(__dirname, `${req.body.img_url[0].filename}-${Date.now()}`)
  await fs.writeFile(filepath, (req.body.img_url[0].data))

  return req.body
})

fastify.listen(3000)

使用以下请求调用它:

代码语言:javascript
运行
复制
curl -X POST \
  http://127.0.0.1:3000/ \
  -H 'content-type: multipart/form-data' \
  -F 'thumb_url=@/home/wks/example-file' \
  -F 'img_url=@/home/wks/example-file' \
  -F 'name=fooo'

您将获得:

代码语言:javascript
运行
复制
{
   "thumb_url":[
      {
         "data":{
            "type":"Buffer",
            "data":[
               97,
               115,
               100,
               10
            ]
         },
         "filename":"example-file",
         "encoding":"7bit",
         "mimetype":"application/octet-stream",
         "limit":false
      }
   ],
   "img_url":[
      {
         "data":{
            "type":"Buffer",
            "data":[
               97,
               115,
               100,
               10
            ]
         },
         "filename":"example-file",
         "encoding":"7bit",
         "mimetype":"application/octet-stream",
         "limit":false
      }
   ],
   "name":"foo",
   "status":1
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60221062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档