使用rxjs ajax()我得到“您的浏览器不支持CORS”

时间:2018-07-31 00:08:28

标签: node.js ajax cors rxjs rxjs6

我不断使用Rxjs 6,

  

错误:您的浏览器不支持CORS

我的代码很简单

import { ajax } from 'rxjs/ajax';

const ajax$ = ajax({
  url: genURL_chan(179),
  crossDomain: true,
  withCredentials: false,
  method: 'POST',
  body: { 'since': 0, 'mode': 'Messages', 'msgCount': 5000},
});

我的代码很简单

/node_modules/rxjs/internal/util/hostReportError.js:4
    setTimeout(function () { throw err; });
                             ^

Error: CORS is not supported by your browser
    at getCORSRequest (/node_modules/rxjs/internal/observable/dom/AjaxObservable.js:27:15)
    at Object.createXHR (/node_modules/rxjs/internal/observable/dom/AjaxObservable.js:93:43)
    at Object.tryCatcher (/node_modules/rxjs/internal/util/tryCatch.js:7:31)
    at AjaxSubscriber.send (/node_modules/rxjs/internal/observable/dom/AjaxObservable.js:159:50)
    at new AjaxSubscriber (/node_modules/rxjs/internal/observable/dom/AjaxObservable.js:147:15)
    at AjaxObservable._subscribe (/node_modules/rxjs/internal/observable/dom/AjaxObservable.js:116:16)
    at AjaxObservable.Observable._trySubscribe (/node_modules/rxjs/internal/Observable.js:43:25)
    at AjaxObservable.Observable.subscribe (/node_modules/rxjs/internal/Observable.js:29:22)
    at Object.<anonymous> (/index.js:17:7)
    at Module._compile (internal/modules/cjs/loader.js:702:30)

2 个答案:

答案 0 :(得分:5)

您需要将createXHR函数放在传递给ajax()调用的实际配置上:

import { XMLHttpRequest } from 'xmlhttprequest'

function createXHR() {
  return new XMLHttpRequest();
}

const ajax$ = ajax({
  createXHR, // <--- here
  url: genURL_chan(179),
  crossDomain: true,
  withCredentials: false,
  method: 'POST',
  body: { 'since': 0, 'mode': 'Messages', 'msgCount': 5000},
});

相关:我也回答了您有关存储库的问题,并提供了更多信息:https://github.com/ReactiveX/rxjs/issues/3978#issuecomment-411472389

答案 1 :(得分:2)

由于某些原因,is a bug从未真正修复过。首先,您必须安装xmlhttprequest

npm install xmlhttprequest;

您必须对其进行一些编辑并添加其中之一

## CommonJS
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

## ES2015
import { XMLHttpRequest } from 'xmlhttprequest';

然后将其放入呼叫ajax()

createXHR: function () {
  return new XMLHttpRequest();
}

应该像这样

import { ajax } from 'rxjs/ajax';
import { XMLHttpRequest } from 'xmlhttprequest';

const ajax$ = ajax({
  url: genURL_chan(179),
  crossDomain: true,
  withCredentials: false,
  method: 'POST',
  body: { 'since': 0, 'mode': 'Messages', 'msgCount': 5000},
});