IE10 Swagger 错误解析失败 JSON/YAML

IE10 Swagger Error Failed to parse JSON/YAML

这是一个更普遍的问题。当我使用 IE11、Chrome、FireFox 等时,我的 Swagger API 工作正常,但 IE10 及以下版本出现错误:failed to parse JSON/YAML 并且在我的 swagger.inspec().state 中返回 "rejected".

以下是我如何实例化我的客户端:

import { API_URI } from '../config/app_config'; // '/accountservice/swagger.json'
import Swagger from 'swagger-client'; //   "swagger-client": "^2.1.17"

export const buildAccountServiceClient = () => {
  const swagger = new Swagger({
    url: (!window.location.origin ? IE_API_URI : API_URI),
    usePromise: true,
  });

  // Reconfigure swagger client to override service path if we're using a reverse proxy:
  // /accountservice/swagger.json -> /accountservice
  // Originally tried setting basePath to null, undefined, and '', but that didn't work
  let basePath;
  if (API_URI.startsWith('/')) {
    basePath = API_URI.substring(0, API_URI.lastIndexOf('/'));
    swagger.then((client) => {
      client.setBasePath(basePath);
      if (typeof(window) !== 'undefined') {
        // use current protocol, so either http or https
        client.setSchemes([window.location.protocol.slice(0, -1)]);
      }
    });
  }
  return swagger;
};

我也在使用代理服务器,这就是为什么我没有将 API_URI 定义为完整 url 而只是路径的原因。

为什么尽管支持 IE10,但它在除 IE10 以外的所有其他浏览器中都能正常工作?

在我的 node_modules 文件夹中深入研究 Swagger-JS 源代码后。

我发现初始化方法试图获取当前 window 位置 "origin" 以添加到传递给构造函数的 url 路径的前面。

由于 IE10 window 对象中没有 origin 键,它正在将 url 翻译为 undefined/swagger.json

为了解决这个问题,我做了以下更改:

node_modules/swagger-client/lib/client.js line:129

  line 126  if(this.url && this.url.indexOf('http:') === -1 && this.url.indexOf('https:') === -1) {
  line 127   // no protocol, so we can only use window if it exists
  line 128   if(typeof(window) !== 'undefined' && window && window.location) {
  line 129     this.url = window.location.protocol + "//" + window.location.host + this.url;
  line 130   }
  line 131 }

在 IE10 中,window 对象不包含名为 location.origin 的对象键,而其他浏览器包含。

所以如果你想让它在 IE10 中工作:

line 129 this.url = window.location.protocol + '//' + window.location.host + this.url;

我正准备尝试提交 PR 以大摇大摆地解决这个问题。

--更新--

如果您不想等待 PR 通过并需要在您这边进行修复:

http://tosbourn.com/a-fix-for-window-location-origin-in-internet-explorer/

或者这是我的解决方法:

const API_URI = '/swagger.json';
const IE_API_URI = `${window.location.protocol}//${window.location.hostname}${(window.location.port ? `:${window.location.port}` : '')}/swagger.json`;

const swagger = new Swagger({
  url: (!window.location.origin ? IE_API_URI : API_URI),
  usePromise: true,
});