Grandizer
Grandizer

Reputation: 3025

Trying to Convert jQuery ajax to ES6 fetch

In an effort to not use jQuery (if ajax is all I need it for) I have the following ajax call that works like a champ.

$.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);
  }
});

I rewrote it in standard javascript using fetch as follows:

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);
});

Which gives me the following error:

Failed to load https://stubidp.sustainsys.com/xxx?SAMLRequest=xxx: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:58659' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Which leads me to add the following attribute:

mode: 'no-cors'

Which gives me the following warning (and does not get to my backed method)

Current.js:78 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://stubidp.sustainsys.com/xxx?SAMLRequest=xxx&RelayState=q-9E0I4hwfJLlInurXY-Yu4g with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Which lead me to add the following:

'X-Content-Type-Options': 'nosniff'

Which gave me the same warning and still did not get to my server.

Any thoughts on what I am still missing?

Update

While looking around the Network tab on Chrome's debugger tools, I noticed the Copy as fetch option. I did this on the working jQuery call and gave me the following 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"
});

When I run that fetch method I get a 400 Bad request error.

Upvotes: 5

Views: 3030

Answers (1)

Grandizer
Grandizer

Reputation: 3025

I would say that thanks to @Wesley Coetzee that got the ball rolling in the right direction. What took care of it for me was the following code:

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'
});

A little back story in case that helps: Everything in the question was based on trying to POST to an ASP.Net Core RazorPage event. After some realization between this new project we are starting and the extra pain you have to go through (not the above code) to convert a response to an actual entity, we changed to using WebAPI. The code in this answer is going to a WebAPI controller and no longer a RazorPage method.

Hope it helps someone.

Upvotes: 4

Related Questions