DTeam 技术日志

Doer、Delivery、Dream

排错:调用 rxjs 的 ajax 报 'CORS is not supported by your browser'

胡键 Posted at — Apr 6, 2021 阅读

症状

调用 rxjs 中的 ajax 方法,结果返回以下错误信息:

        throw new Error('CORS is not supported by your browser');
^
Error: CORS is not supported by your browser
    at getCORSRequest (./node_modules/rxjs/internal/observable/dom/AjaxObservable.js:28:1)
    at Object.createXHR (./node_modules/rxjs/internal/observable/dom/AjaxObservable.js:94:1)
    at AjaxSubscriber.module.exports.__webpack_modules__.2939.AjaxSubscriber.send (./node_modules/rxjs/internal/observable/dom/AjaxObservable.js:167:1)
    at new AjaxSubscriber (./node_modules/rxjs/internal/observable/dom/AjaxObservable.js:149:1)
    at AjaxObservable.module.exports.__webpack_modules__.2939.AjaxObservable._subscribe (./node_modules/rxjs/internal/observable/dom/AjaxObservable.js:117:1)
    at AjaxObservable.Observable._trySubscribe (./node_modules/rxjs/internal/Observable.js:44:1)
    at AjaxObservable.Observable.subscribe (./node_modules/rxjs/internal/Observable.js:30:1)
    at MapOperator.module.exports.__webpack_modules__.8230.MapOperator.call (./node_modules/rxjs/internal/operators/map.js:32:1)
    at Observable.subscribe (./node_modules/rxjs/internal/Observable.js:25:1)

原因

问题的根源可不像看上去的那样明了,并非你去查 api 手册加上跟 cors 相关的配置就可以解决的。这个错误跟这个 issue 有关,虽然其状态是 closed 但其实一直并未修复,起码在当前的 rxjs 6 上依旧有这样的问题。

解决

解决之道在上述 issue 的评论中已经给出:

  1. 安装 xmlhttprequest (对于 TypeScript 则是 xmlhttprequest-ts
  2. 然后采用下面类似的代码:
function simpleAsync() {
  ajax({
    url: 'https://blog.dteam.top/posts.html',
    // 记得 import {XMLHttpRequest} from 'xmlhttprequest-ts';
    createXHR: () => new XMLHttpRequest(),
  })
    .pipe(
      ...
    )
    .subscribe(res => {
      ...
    });

其余则按需自行查阅文档进行配置吧,😄


友情链接


相关文章