React/Redux + 超级代理,第一个呼叫被终止

React/Redux + super agent, first call gets terminated

我正在编写一个 react-redux 应用程序,我正在使用 superagent 在我的中间件中进行一些服务调用。我发现了一个非常奇怪的行为,第一次调用我的搜索 api 总是被终止。我尝试过等待 10-30 秒再进行第一次调用,并记录过程中的每一步,但我似乎无法确定为什么会发生这种情况。

我的动作创作者看起来像

export function getSearchResults(searchQuery) {
return {
        query: searchQuery,
        type: actions.GO_TO_SEARCH_RESULTS
    }
}

它在这里命中了中间件逻辑:

var defaultURL = '/myServer/mySearch';

callPendingAction();

superagent.get(defaultURL)
        .query({query: action.query})
        .end(requestDone);


//sets state pending so we can use loading spinner
function callPendingAction() {
    action.middlewares.searchIRC.readyState = READY_STATES.PENDING;
    next(action);
}

//return error or response accordingly
function requestDone(err, response) {
    console.log("call error", err);
    const search = action.search;
    if (err) {
        search.readyState = READY_STATES.FAILURE;
        if (response) {
            search.error = response.err;
        } else if (err.message) {
            search.error = err.message;
        } else {
            search.error = err;
        }
    } else {
        search.readyState = READY_STATES.SUCCESS;
        search.results = fromJS(response.body);
    }
    return next(action);
}

即使呼叫终止,查询也是正确的,我收到此错误消息:

Request has been terminated
Possible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.
at Request.crossDomainError (http://localhost:8000/bundle.js:28339:14)
at XMLHttpRequest.xhr.onreadystatechange (http://localhost:8000/bundle.js:28409:20)

好像也是每次刷新页面。

我似乎找不到任何关于为什么会发生这种情况的线索,第一次调用失败似乎无关紧要,但在第一次终止调用之后就没问题了。非常感谢任何输入,谢谢!

更新:看来这与 chrome 有关,我在 Version 47.0.2526.80 (64-bit)。这个应用程序是另一个应用程序中的 iframe,我认为这会导致 chrome 出现问题,因为当我在 firefox 中尝试这个时没有问题。奇怪的是只有第一次调用给出了 CORS 问题,然后似乎在这之后得到了纠正。如果有人有意见或解决方法,我将不胜感激。感谢阅读。

我不知道副作用,但您遇到了 CORS 错误。将 .withCredentials() 方法添加到您的请求中。

来自超级代理docs:

The .withCredentials() method enables the ability to send cookies from the origin, however only when "Access-Control-Allow-Origin" is not a wildcard ("*"), and "Access-Control-Allow-Credentials" is "true".

这应该可以解决问题:

superagent.get(defaultURL)
        .query({query: action.query})
        .withCredentials()
        .end(requestDone);

可以找到有关跨源资源共享的更多信息here

遇到了同样的问题,感谢answer provided by @KietIG on the topic ReactJS with React Router - strange routing behaviour on Chrome

答案与 CORS 无关。请求已取消,因为 Chrome 在请求中途离开了页面。发生这种情况是因为未在其中一个表单提交处理程序中调用 event.preventDefault()。似乎 Chrome 处理此问题的方式与其他浏览器不同。

有关详细信息,请参阅上面的答案 link。

在我的例子中,当我试图在客户端设置一个随机 HTTP 请求 header(比如 X-Test)并且 AWS Lambda 在 OPTIONS 请求期间拒绝了它或者其他什么时发生了这种情况做到了。