Trying to Convert jQuery ajax to ES6 fetch - javascript

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.

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.

Related

Getting parse error while fetching text file content in JQuery

I am trying to fetch data from text file which resides on server. I have access of that location and able to see content when I put URL in browser tab.
I am trying to make AJAX call and get file content, but I am getting Error: Uncaught SyntaxError: Unexpected identifier
Code
function logResults(json){
console.log(json);
}
$.ajax({
url: u,
dataType: "jsonp",
jsonpCallback: "logResults"
});
on console,
I tried below code too, but same result,
$.ajax({
type: 'GET',
url: u,
crossDomain: true,
dataType: 'jsonp',
async: false,
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function(succ) {
console.log("Success: ", succ)
},
error: function(err) {
console.log("Error: ", err)
}
});
This code is always going into error block.
You said:
dataType: "jsonp",
But the URL is responding with:
Deployment automatically finished…
Which is not JSONP, it is plain text.
You get the error when it tries to execute the plain text as JSONP.
Don't put wrong information in the dataType field.
async: false,
That's deprecated. Don't use it. It's also pointless since you are using callbacks.
It's also incompatible with JSONP so it is ignored (until you remove the incorrect dataType).
crossDomain: true,
This has no effect unless you are making a:
non-JSONP request
to the same origin
which gets redirected to a different origin
… which is very rare.
headers: {
"Access-Control-Allow-Origin": "*"
},
Access-Control-Allow-Origin is a response header. It doesn't belong the request. Trying to add it to the request will cause extra problems as it will make the request preflighted.
(At least, that would be the case if you hadn't said dataType: 'jsonp' because adding request headers is incompatible with JSONP).
All you need on the client
The only code you need on the client is:
function logResults(result){
console.log(result);
}
$.ajax({
url: u,
success: logResults
});
The server you are requesting the data from will need to use CORS to grant you permission to access it if it is a cross-origin request.
It is because you have added dataType as jsonp, so that it will try to parse the response to JSON and if the response is not a JSON it will throw error.

Get 401 when using ajax call to retrieve data from couchdb

I try to use ajax call in js file to retrieve data from couchdb.
But I got the 401 error:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Here is my js code:
var locate_data = $.ajax({
url: 'http://admin:mypassword#localhost:5984/database_name',
type:'GET',
dataType: "json",
success: function(data){
console.log("successfully loaded."),
alert(data);
},
error: function(xhr) {
console.log("error"),
alert(xhr.statusText)
}
})
I can use 'curl GET' to get the data from couchdb by using the terminal.
What is the problem? and how can I fix it?
You could use Basic access authentication where requests contain a header field in the form of Authorization: Basic <credentials>, where credentials is the Base64 encoding of username and password, joined by a single colon ':'.
This answer explains how to do the same in the context of Angular. I'm not using Ajax myself but I suppose it should look something like this.
$.ajax({
url: 'http://localhost:5984/database_name',
type:'GET',
headers: {
'Accept': 'application/json',
'Content-type', 'application/json',
'Authorization': 'Basic ' + btoa("<username>:<password>")
},
xhrFields: {
withCredentials: true
},
...

in Ajax, how to write "headers" for multiple condition?

as a beginner, I have some problems in using Ajax (with Discogs API) .. to get a discogs request token, discogs is saying
Include the following headers with your request:
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback"
User-Agent: some_user_agent
https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow
but, how to write this header?
below is my trying code, but I know this is not proper.
$.ajax({
type: "GET",
url: "https://api.discogs.com/oauth/request_token",
dataType: 'jsonp',
headers: {
ContentType: "application/x-www-form-urlencoded",
Authorization: OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback",
UserAgent: some_user_agent,
}
success: function (data) {
console.log(data);
document.getElementById("content").innerHTML += "<br>" + `${data}`;
},
error: function (error) {
console.log(error);
}
});
You said:
dataType: 'jsonp',
It isn't possible to specify headers for JSONP requests.
The API can't be using JSONP. Set the dataType to the format they are using.
The documentation says:
When you create a new application, you’ll be granted a Consumer Key and Consumer Secret, which you can plug into your application and start making authenticated requests. It’s important that you don’t disclose the Consumer Secret to anyone.
Putting those in your client-side code will disclose them to all your visitors.
The request to that end point should be made from server-side code.

JIRA REST API for authentication in jquery

I'm trying to authenticate my user by following code.
$.postJSON = function(url, data, callback, errorCallback) {
return jQuery.ajax({
'type': 'POST',
'url': url,
'contentType': 'application/json',
'data': data,
'dataType': 'json',
'success': callback,
'error': errorCallback
});
};
logindata = "{ 'username': admin, 'password': '********'}";
$.postJSON ('https://****.****.net/rest/auth/1/session', logindata, function (data, textStatus) {
alert (textStatus);
}, function (objStatus) {
alert (JSON.stringify(objStatus));
});
but, got 2 error
Failed to load resource: the server responded with a status of 415 ()
Failed to load https://jira URL/rest/auth/1/session: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://...:****' is therefore not allowed access. The response had HTTP status code 415.
any one can help me? why its happening ?
For your first error, add
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'data': JSON.stringify(data),
to jQuery.ajax. Check POST JSON fails with 415 Unsupported media type, Spring 3 mvc for more details
For your second error, this is a CORS issue. Use a plugin for your browser. Download this plugin https://chrome.google.com/webstore/detail/cors-toggle/jioikioepegflmdnbocfhgmpmopmjkim?utm_source=chrome-app-launcher-info-dialog and enable cors.

xhr.getAllResponseHeaders() returns only one header

We have Node.js as a server which helps in getting us remote rest service, from client html I am trying to get response headers from the jQuery Ajax call using below code:
$.ajax({
type: "get",
url: newUrl,
crossDomain: true,
cache: false,
dataType: "json",
contentType: "application/json; charset=UTF-8",
success: function(data, textStatus, xhr) {
var responseText = JSON.stringify(data);
alert(xhr.getAllResponseHeaders());
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
But the problem is, I only get one one response header: Content-Type: application/json remaining things are ignored. From my research I found that I need to add Access-Control-Allow-Headers to make that available. So in Node I tried like this:
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Origin'
});
But still I get only the one header Content-Type. Can you help in identifying this issue? By the way, it's a cross domain calls.
Finally I am able to resolve this issue, from the Node.js side.
I added both
Access-Control-Expose-Headers and Access-Control-Allow-Headers
to the response header in node.js. This solved my issue. Earlier I was having only Access-Control-Allow-Headers.
What header do you want? Add it to Access-Control-Allow-Headers. (I'm not sure whether CORS header show up or not, though you probably won't need them.)
'Access-Control-Allow-Headers': 'Header1, Header2, Header3'

Categories

Resources