I'm picking up on someone else work with a custom template, and I'm getting the following error:
Failed to load https://api.worldpay.com/v1/orders: Response to the preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxx.xxx.xxx.xxx' is therefore not allowed access.
Here is the code that sends the AJAX request:
$.ajax({
type: "POST",
url: "https://api.worldpay.com/v1/orders",
dataType: 'json',
async: false,
headers: {
'Access-Control-Allow-Origin': '*',
"Authorization": worldPayServiceKey
},
data: JSON.stringify(options),
success: function (response){
if (response.paymentStatus == 'SUCCESS') {
current_booking.payment = obj.response;
} else {
alert("Sorry, there was a problem with your payment. We will send you an invoice instead.");
}
makeBooking();
}
});
I've had a similar problem with CORS before, but I haven't seen the preflight error before. Can anyone help, please?
please remove the Access-Control-Allow-Origin header from request header. that is a server side header.
Then add Content-Type as,
application/x-www-form-urlencoded,multipart/form-data or text/plain depending on what you are sending with the request. for example,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": worldPayServiceKey
},
The only allowed values for the Content-Type header are:
> - application/x-www-form-urlencoded
> - multipart/form-data
> - text/plain
for more info, read the MDN DOC.
Hope It helps. good luck.
Related
I have an Ajax request that looks like this:
$.ajax({
url: "http://some-api.com/endpoint/",
type: "POST",
contentType: "application/json",
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
data: '"data": "20200312',
dataType: "json",
success: function (data) {
console.log(data);
}
});
});
I've tried almost everything, but for some reason I keep getting the same error:
Access to XMLHttpRequest at 'http://some-api.com/endpoint/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
What am I doing wrong or missing. I am using Django as my backend. Also it works in Postman, but doesn't work through Ajax
Here when I trying to print response in browser console. It shows this error
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://script.google.com/macros/s/AKfycbwmqG55tt2d2FcT_WQ3WjCSKmtyFpkOcdprSITn45-4UgVJnzp9/exec?url=http://35.230.52.177:8095/OneSoftTracking/rest/tracking/consignment/AE101632?hostname=aastha-enterprises.com&callback=jQuery1124008693115102408444_1561964934754&_=1561964934755 with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.`
While when I get data in Postman like:
This warning or error showing :
This is my code :
var settings = {
async: true,
crossDomain: true,
crossOrigin: true,
url: "http://35.230.52.177:8095/OneSoftTracking/rest/tracking/consignment/AE101632?hostname=aastha-enterprises.com",
method: "GET",
"headers": {
"Content-Type":"application/json",
"Access-Control-Allow-Origin":"*",
'Access-Control-Allow-Methods':'GET',
'Access-Control-Allow-Credentials' : true,
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "bea2b074-eefc-473e-84d7-b680a07ed7df,dafa4f5c-94af-4efe-967f-75a9fe185a1e",
},
success: function(data) {
console.log("+++++SuCCESS");
console.log(data);
},
error: function(error){
console.log("NOT SUCCEED");
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
You haven't shown us your real code.
The error message clearly shows a callback in the query string which isn't in your URL and shouldn't be added because you haven't said dataType: 'jsonp' in the jQuery ajax configuration.
Your real code is configured to use JSONP.
A JSONP response is a JavaScript program (specifically one which calls a single function with a set of arguments). The response you are getting from the server is an HTML document (the content type is text/html and not application/javascript).
The CORB error is the browser telling you that the response is HTML and not JSONP so it is refusing to try to execute it.
The Postman screenshot shows that you are expecting a JSON (still not JSONP) response (but you aren't getting that either).
You need to either:
Change the server to respond with JSONP
Change the request to ask for the correct data (and possibly also change the server to grant you permission to read it using CORS)
Further reading:
What is JSONP, and why was it created?
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
Notes about your code:
async: true,
This is the default, get rid of it
crossDomain: true,
This is the default for cross origin requests, get rid of it.
crossOrigin: true,
This is the default for cross origin requests, get rid of it.
method: "GET",
This is the default, get rid of it
"Content-Type": "application/json",
You are making a GET request. There is no request body to describe the type of. This is nonsense. Get rid of it.
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Credentials': true,
These are response headers, not request headers. Putting them on the request is nonsense. Get rid of them.
"Accept": "*/*",
The default is almost certainly going to be fine. You probably don't need to override it.
"Cache-Control": "no-cache",
The main config option "cache" is probably a better choice than explicitly setting the header.
"Postman-Token": "bea2b074-eefc-473e-84d7-b680a07ed7df,dafa4f5c-94af-4efe-967f-75a9fe185a1e",
The odds of your server caring about this are remote. You can probably get rid of this.
I'm trying to use API to get information about a specific user based on user ID. I need to use basic auth and pass some headers with my call.
I'm getting this:
Cross-Origin Read Blocking (CORB) blocked cross-origin response "rest/user/getProfile?callback=jQuery224033348109431646855_1548684613983&userId=24068..." with MIME type text/plain.
My code:
$.ajax
({
type: 'GET',
crossDomain: true,
async: false,
url: 'example_URL_/api/user/getProfile',
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic ZHVubmVzYXBpskjoi43u5409543o9tI654kjhugjy"); },
dataType: 'jsonp',
data: { "Id": "1234" },
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
is there anything I'm missing?
You said:
dataType: 'jsonp',
… so jQuery makes a JSONP request (i.e. inserts a <script> element).
The browser makes a request to the URL and the server said:
Content-Type: text/plain
Since a plain text document is not a JavaScript program, the browser refused to execute it and threw a CORB error instead.
A JSONP response must be application/javascript, not text/plain.
You need to either:
Not make a request for JSONP
Change the server to respond with JSONP
Aside: Since you are using JSONP, the type, crossDomain, async, headers, and xhr.setRequestHeader properties have no effect.
Since you said you needed to set basic auth, that rules out option two. You can't use JSONP for this.
In your API configure CORS to accept all domains, or enter the domain that you're using to send the request from.
If your API is created by PHP here is an example:
<?php
header("Access-Control-Allow-Origin: *");
Or if you are using a third party API, try to see the documentation. I'm sure there will be a part talking about CORS.
I'm having troubles with an AJAX request. I was getting the below error:
Error: Access is denied
I tried this jQuery AJAX request:
$.support.cors = true;
$.ajax({
url: 'http://testwebsite.com/test',
type: "GET",
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
headers: {
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': 'http://testwebsite/test',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true'
},
xhrFields: {
withCredentials: true
},
success: function(data) {
alert("Data from Server" + JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
alert("You can not send Cross Domain AJAX requests: " + errorThrown);
}
});
Can anyone kindly let me know what I am missing. Thanks in advance.
As rory-mccrossan mentioned in a comment, CORS protection is designed so that a website cannot directly access the content of another website (in a browser) unless the website being accessed agrees to it.
It would completely ruin the point of CORS if a site just has to send some headers in order to circumvent the defence
Instead, you will need to use a CORS proxy. It's a server that when given a request like yourCORSproxy.example.com/http://testwebsite/test would load the page and return it, but with CORS allowed (like a normal proxy but with CORS enabled).
One of these CORS proxies is https://crossorigin.me, but at the time of writing this it is down. It might be more stable if you simply create your own proxy.
tl;dr: testsite.test should be sending the headers on its response. You should not be sending the headers on your request.
When I add header HTTP_X_REQUESTED_WITH in ajax for request to another server then it give erorr as Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.xxxxxxxxxxxx.com/checkurl.php?action=xxxxxxx. This can be fixed by moving the resource to the same domain or enabling CORS.
and if I remove this header it working properly.
I have many ajax request so I use this format to add header in all ajax request
$(document).ajaxSend(function (event, jqxhr, settings) {
jqxhr.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest')
});
and my ajax is :
$.ajax({
url:sitePath+'Xxxxxxxxx/checkurl.php?action=Pages&page='+actionPage,
type :'POST',
crossDomain:true,
success : function(data){
hideLoadingDiv();
if(data.getElementsByTagName("message")[0].getElementsByTagName("messageType")[0].childNodes[0].nodeValue=="SUCCESS")
{
document.getElementById(divID).innerHTML=data.getElementsByTagName("PageBody")[0].childNodes[0].nodeValue+'<span><a onclick="return checkRegistrationValidation();" href="javascript:void(0);" class="orengeBtn">Back</a></span>';
displayDiv(divID);
}
else if(data.getElementsByTagName("message")[0].getElementsByTagName("messageType")[0].childNodes[0].nodeValue=="ERROR")
{
showErrorMessage(data.getElementsByTagName("message")[0].getElementsByTagName("messageText")[0].childNodes[0].nodeValue);
}
else
{
generalError();
}
},
error:function(xhr,ajaxOptions, thrownError){
hideLoadingDiv();
if(xhr.status==200){
generalError();
}
else{
networkError();
}
if(debugMode==1){
displayAjaxError(xhr,thrownError);
}
}
});
and in my server file I use
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type')
but it give error every time when I add header. And after remove working properly. Please help.
You can find answer here:
Cross-Domain AJAX doesn't send X-Requested-With header
You have to either add the headers manually in your ajax:
$.ajax({
url:sitePath+'Xxxxxxxxx/checkurl.php?action=Pages&page='+actionPage,
type :'POST',
crossDomain:true,
headers: {'X-Requested-With': 'XMLHttpRequest'}
or make the request not crossdomain:
$.ajax({
url:sitePath+'Xxxxxxxxx/checkurl.php?action=Pages&page='+actionPage,
type :'POST',
crossDomain:false,