Fetch API and Cordova

Fetch API and Cordova

本文关键字:Cordova and API Fetch      更新时间:2023-09-26

我在一起使用Cordova和fetch API时遇到问题。我正在执行以下代码

fetch(BASE_URL + '/auth/login', {
  method: 'post',
  credentials: 'include',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: transformRequest({username: email, password: password})
}).then(response => {
      console.log(response.headers.get('X-AuthToken'))
});

在浏览器中执行代码时,将正确检索并记录"X-AuthToken"标头。当我在我的 Cordova 应用程序中打包时运行相同的代码时,"X-AuthToken"标头为空。此外,奇怪的是,在检查响应服务器端和在网络上嗅探时,我可以完美地看到标头集,因此我完全确定标头在那里(只是它不是由获取 API 返回的);事实上,当使用等效的XMLHttpRqeuest时,标头设置正确:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", BASE_URL + /api/auth/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=username&password=password");
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       console.log (xhttp.getResponseHeader('X-AuthToken'));
    }
}

值得指出的是,当我尝试转储其他常见标头(如编译指示、缓存控制等)时,...它们已正确记录。它就像获取 API 正在过滤标头并删除非标准标头一样。其他人是否遇到同样的问题?我错过了什么吗?

很好的问题,你正在最前沿发展。我现在会坚持使用XMLHTTPRequest。Fetch api 在 webkit 中未正确实现。请参阅 webkit bugzilla bug 151937