You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swagger 发送 POST 请求时缺少 Content-Type 请求头

问题原因

Content-Type 请求头丢失和 bearerAuth 鉴权配置没有直接关系。

Swagger UI 不会主动推断请求体类型,只会根据 OpenAPI 定义中显式声明的请求体媒体类型,自动添加对应 Content-Type 头。你是在切换到 OpenAPI 3.0 配置的同时添加了鉴权规则,才误以为是鉴权导致的问题,本质是旧版 Swagger 2.0 的接口注解在 3.0 规范下不生效。
此外你的基础配置存在两处语法问题:

  • servers 是 OpenAPI 3.0 的根级字段,不能嵌套在 info 对象内部
  • 标准 Bearer Token 鉴权的安全方案类型应为 http,当前配置的 apiKey 类型不会自动拼接 Bearer 前缀,且 scheme 字段对 apiKey 类型无效
修复步骤

1. 修正全局配置

调整后的完整配置如下,全局鉴权规则可以保留,不会影响普通请求头:

const swaggerOptions = {
  definition: {  
    openapi: '3.0.0',  
    info: {            
      version: "1.0.0",
      title: "Diniz API",
      description: "Rest API Diniz",
    },
    // 移至根层级
    servers: ['http://localhost:5000'],
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT' // 可选,标识Token格式
        },
      }
    },
    // 全局鉴权配置无需改动
    security: [{ 
      bearerAuth: [], 
    }],
  },
  apis: ['routes/*.js']
}

2. 为带请求体的接口声明媒体类型

在路由对应的 JSDoc 注解中,给 POST/PUT 等携带请求体的接口添加 requestBody 配置,明确声明 Content-Type。
以最常见的 JSON 请求为例:

/**
 * @swagger
 * /your/api/path:
 *   post:
 *     summary: 示例POST接口
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - username
 *             properties:
 *               username:
 *                 type: string
 *               password:
 *                 type: string
 *     responses:
 *       200:
 *         description: 请求成功
 */
router.post('/your/api/path', yourController)

如果是文件上传或 form-data 请求,把 application/json 替换为 multipart/form-data;普通 urlencoded 表单则替换为 application/x-www-form-urlencoded。

验证方式

重启服务后打开 Swagger 文档页面,对应 POST 接口的请求体区域会显示你声明的媒体类型。点击「Try it out」发起请求时,会同时携带正确的 Content-Type 和 Authorization 请求头。

内容的提问来源于stack exchange,提问作者Pedro Melo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 06:45:02