xhr.getAllResponseHeaders() returns only one header - javascript

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'

Related

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
},
...

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.
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.

Getting error while calling a remote web API

I am working website and hitting a third party api but getting an error
No 'Access-Control-Allow-Origin' header is present on the requested resource
Ajax:
var headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept', 'application/json');
headers.append('content-type', 'application/json');
headers.append('AuthToken', '2948f47085e9d8ecd95bd21ebe024a01516105f9')
headers.append('Access-Control-Allow-Origin', 'http://localhost:61030/Test.aspx');
headers.append('Access-Control-Allow-Credentials', 'true');
$.ajax({
crossDomain: true,
type: "GET",
url: "https://api.travelcloudpro.eu/v1/cache/flyfrom?origin=DEL&pointOfSale=US",
//headers: { '[{"key":"AuthToken","value":"2948f47085e9d8ecd95bd21ebe024a01516105f9","description":""}]': 'some value' },
// header: { 'AuthToken': '2948f47085e9d8ecd95bd21ebe024a01516105f9' },
header:headers,
dataType: "json",
data:{},
success: function (data) {
debugger;
var flightresponse = data;
//alert($("#city").val());
}
});
While calling from postman it works fine.
I don't know what is missing, TIA.
if i change datatype json to jsonp then getting this error :- enter image description here
i guess as you mentioned "third party api" you are sending request to a server with different ip address (or port number) which makes a CORS error(Cross-Origin Resource Sharing) in most browsers like firefox and chrome.
+here you can read more about why it happens.+
you need to add a CORS Filter which is discussed +here+.
I`m not a .net programmer but i hope it could help.

JSONP ajax call executes error method its response is 200 ok

Here is my api calling its response is 200 OK but it not entered into the success method I have no clue where i am doing wrong. I enable CORS on server side.
$( document ).ready(function() {
$.ajax({
url: 'https://localhost:44300/api/apim/{{Product.Id}}/'+email+'/',
dataType: 'jsonp',
success: function(data) {
alert("success");
if(data===true){
$('#subscribe').prop('disabled', true);
$('#subscribe').text('Is Pending');
}
else
{
}
},
error: function(err)
{
alert("Error");
},
type: 'GET'
});
});
Image
You said dataType: 'jsonp', but the server said content-type: application/json.
JSONP is application/javascript because it isn't JSON (it's a hack to get around the same origin policy from before we had CORS, since you are using CORS, it is pointless … well, you claim you are using CORS, but I don't see an Access-Control-Allow-Origin header in the response).
Remove dataType: 'jsonp' and let jQuery work out the type of data from the content-type response header.

No response for ajax PUT, but response on ajax GET and POST

Making a same-domain (http://example.host.com -> http://example.host.com) POST, the responseXML contains the expected data. Making the same request, but as a PUT, the responseXML is null for a successful request. I'm using jQuery.ajax, but I tested a manual implementation as well with the same results.
var settings = {
url: '//' + window.location.host + window.location.pathname,
type: getRequestType(),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(parms),
error: function(jqxhr, status, error) {
console.log('error');
},
success: function(data, status, jqxhr) {
console.log('success:', data);
}
};
$.ajax(settings);
I am using a very simple server request handler that returns a simple json-formatted string.
#require_http_methods(["PUT"])
def proxy_update(request):
out = {
'type': 'update',
'success': True
}
return HttpResponse(json.dumps(out), mimetype="application/json")
What is the explanation for this?
Per jQuery documentation, not all browsers support all verbs. Quite possibly the browser you are using does not support the PUT verb. Try another browser. If the failure is not with the browser then it is also possible that the server may be configured to ignore the PUT verb.

Categories

Resources