尝试将 jQuery ajax 转换为 ES6 fetch

Gra*_*zer 5 javascript jquery cors fetch-api cross-origin-read-blocking

为了不使用 jQuery(如果ajax这是我所需要的),我进行了以下ajax调用,效果非常好。

$.ajax({
  type: "POST",
  url: "/Tests/EEG/Portable/Index?handler=Testing",
  beforeSend: function (xhr) {
    xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
  },
  data: JSON.stringify(model),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
    alert("Success");
  },
  failure: function (response) {
    alert(response);
  }
});
Run Code Online (Sandbox Code Playgroud)

我用标准 JavaScript 重写了它,fetch如下所示:

fetch("/Tests/EEG/Portable/Index?handler=Testing", {
  method: "POST",
  headers: {
    'XSRF-TOKEN': $('input:hidden[name="__RequestVerificationToken"]').val(),
    'content-type': 'application/json; charset=utf-8'
  },
  body: JSON.stringify(model)
}).then(checkStatus)
  .then(function (data) {
    alert("second then");
}).catch(function (error) {
  console.log(error);
});
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

无法加载https://stubidp.sustainsys.com/xxx?SAMLRequest=xxx:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问来源“ http://localhost:58659 ”。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

这导致我添加以下属性:

mode: 'no-cors'
Run Code Online (Sandbox Code Playgroud)

这给了我以下警告(并且没有到达我支持的方法)

Current.js:78 跨源读取阻止 (CORB) 阻止跨源响应https://stubidp.sustainsys.com/xxx?SAMLRequest=xxx&RelayState=q-9E0I4hwfJLlInurXY-Yu4g,MIME类型为 text/html。有关更多详细信息,请参阅https://www.chromestatus.com/feature/5629709824032768 。

这导致我添加以下内容:

'X-Content-Type-Options': 'nosniff'
Run Code Online (Sandbox Code Playgroud)

这给了我同样的警告,但仍然没有到达我的服务器。

对我还缺少什么有什么想法吗?

更新

在浏览 Chrome 调试器工具的“网络”选项卡时,我注意到了这个Copy as fetch选项。我在工作中的 jQuery 调用中执行了此操作,并给出了以下 JavaScript:

fetch("http://localhost:58659/Tests/EEG/Portable/Index?handler=Testing", {
  "credentials": "include",
  "headers": {},
  "referrer": "http://localhost:58659/Tests/EEG/Portable",
  "referrerPolicy": "no-referrer-when-downgrade",
  "body": JSON.stringify(model),
  "method": "POST",
  "mode": "cors"
});
Run Code Online (Sandbox Code Playgroud)

当我运行该fetch方法时,出现400 Bad request错误。

Gra*_*zer 4

我想说,这要感谢@Wesley Coetzee,让事情朝着正确的方向发展。为我解决的是以下代码:

fetch('/api/Tests/Single', {
  credentials: 'include',
  headers: {
    'XSRF-TOKEN': $('input:hidden[name="__RequestVerificationToken"]').val(),
    'content-type': 'application/json; charset=utf-8',
    'X-Content-Type-Options': 'nosniff'
  },
  referrer: '/Tests/EEG/Portable',
  referrerPolicy: 'no-referrer-when-downgrade',
  body: JSON.stringify(model),
  method: 'POST',
  mode: 'cors'
});
Run Code Online (Sandbox Code Playgroud)

一个小背景故事以防万一有帮助:问题中的所有内容都是基于尝试 POST 到 ASP.Net Core RazorPage 事件。在意识到我们正在启动的这个新项目以及将响应转换为实际实体所必须经历的额外痛苦(不是上面的代码)之后,我们改为使用 WebAPI。此答案中的代码将转到 WebAPI 控制器,而不再是 RazorPage 方法。

希望它能帮助某人。