YMFE/yapi · error

返回数据格式不是 JSON

Error message

返回数据格式不是 JSON

What it means

projectController.swaggerUrl proxies a user-provided swagger URL server-side. If the response body is null or not an object (i.e. not JSON — an HTML page, string, etc.), it throws '返回数据格式不是 JSON'; the catch wraps it in a 402 response.

Source

Thrown at server/controllers/project.js:1130

    projectList = commons.filterRes(projectList, projectRules);
    groupList = commons.filterRes(groupList, groupRules);
    interfaceList = commons.filterRes(interfaceList, interfaceRules);
    let queryList = {
      project: projectList,
      group: groupList,
      interface: interfaceList
    };

    return (ctx.body = yapi.commons.resReturn(queryList, 0, 'ok'));
  }

  // 输入 swagger url 的时候 node 端请求数据
  async swaggerUrl(ctx) {
    try {
      const { url } = ctx.request.query;
      const { data } = await axios.get(url);
      if (data == null || typeof data !== 'object') {
        throw new Error('返回数据格式不是 JSON');
      }
      ctx.body = yapi.commons.resReturn(data);
    } catch (err) {
      ctx.body = yapi.commons.resReturn(null, 402, String(err));
    }
  }
}

module.exports = projectController;

View on GitHub (pinned to 59bade3a8a)

Solutions

  1. Use the JSON spec URL (e.g. http://host/v2/api-docs or /swagger.json), not the swagger UI HTML page
  2. curl the URL from the server and confirm the body is JSON
  3. Ensure the endpoint does not return a login/HTML page due to auth redirects
  4. Check that the response Content-Type is application/json

Example fix

// before
const { url } = ctx.request.query; // url = 'http://host/swagger-ui/index.html'
// after
// import with url = 'http://host/v2/api-docs' (returns JSON object)
Defensive patterns

Strategy: validation

Validate before calling

async function isJsonSpecUrl(url){
  try { const r = await fetch(url, { headers: { Accept: 'application/json' } }); const j = await r.json(); return j && typeof j === 'object'; } catch (e) { return false; }
}

Type guard

function isJsonObject(v){ return v != null && typeof v === 'object' && !Array.isArray(v); }

Try / catch

try {
  const { data } = await axios.get('/api/project/swagger_url?url=' + encodeURIComponent(url));
  if (data.errcode) throw new Error(data.errmsg);
} catch (e) {
  console.error('Swagger URL must return a JSON object:', e.message);
}

Prevention

When it happens

Trigger: User enters a swagger URL in the import UI whose response is not a JSON object — e.g. a swagger-ui HTML page, an XML/WSDL doc, or an empty response.

Common situations: Pasting the swagger UI page URL instead of the JSON spec URL; endpoint returns CSV/text; wrong endpoint behind a redirect; axios auto-parsing disabled so data is a string.

Related errors


AI-assisted analysis of YMFE/yapi@59bade3a8a (2026-08-29). Data as JSON: /api/errors/72c510dd5622e696. Report an issue: GitHub.