I am writing both server and client using visual studio 2015.
The following problem occurs in Chrome and FireFox, but works perfect in Explorer.
I am doing a Rest post call using AJAX to my server, the AJAX code:
function CheckIntegrityExecution() {
var request = ...
var reqJson = JSON.stringify(request);
$.ajax({
type: "POST",
url: "http://localhost:55857/api/post/flow",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: reqJson,
success: function (jsonData) {
...
},
error: function () {
alert("error");
}
});
}
Initially I was getting 405 error, and this was fixed with adding
var cors = new EnableCorsAttribute("http://localhost:55857", "*", "*");
config.EnableCors(cors);
To the Register function in Global.asax:
public static void Register(HttpConfiguration config)
Now I getting the following error:
XMLHttpRequest cannot load http://localhost:55857/api/post/flow. Response for preflight has invalid HTTP status code 400
The method signature in my server is
[Route("api/post/flow")]
public HttpResponseMessage PostCommand([FromBody] dynamic value)
And I have these configuration in my Web.config in the WebApi.
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="OPTIONS, TRACE, GET, HEAD, POST, PUT" />
<add name="Access-Control-Allow-Headers" value="Origin, Content-Type, Authorization, Accept, X-Requested-With" />
</customHeaders>
I notice that if I delete
contentType: "application/json; charset=utf-8",
from the Ajax request I will work, but I will not get the data in my server.
I have no ideas what to do, tried everything.
The solution was to add the following to the Global.asax file
protected void Application_BeginRequest()
{
var context = HttpContext.Current;
var response = context.Response;
if (context.Request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
response.End();
}
}
Related
I have the following code in JS:
// Function to feed the API
function FeedAPI() {
// Define the API endpoint URL
var apiUrl = "https://ifthenpay.com/api/gateway/paybylink/XXX-XXXX";
// Define the JSON API body
var apiData = {
"id": "1234",
"amount": ValueSelected(),
"description": $('#name').val(),
"lang": "en",
"expiredate": "",
"accounts": "",
"selected_method": PaymentSelected()
};
console.log("API data: ", apiData);
// Use jQuery's $.ajax() function to make the request
$.ajax({
type: "POST",
url: apiUrl,
data: JSON.stringify(apiData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
console.log("API response: ", response);
},
error: function(xhr, status, error) {
console.error("Error: ", error);
}
});
}
But get this error:
Access to XMLHttpRequest at 'https://ifthenpay.com/api/gateway/paybylink/XXX-XXXX' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
I'm using Plesk on Windows and already tried to set my web.config file to the following:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
At this point, I tried everything... Can someone help??
So, I fixed my issue by just changinging the method of the API Integration to "GET".
Here is the code:
function FeedAPI() {
// Define the API endpoint URL
var apiUrl = "https://ifthenpay.com/api/gateway/paybylink/get";
// Define the query parameters
var apiParams = {
"gatewaykey": "XXX-XXXX",
"id": "1234",
"amount": ValueSelected(),
"description": $('#name').val(),
"lang": "en",
"expiredate": "",
"accounts": "XXX|YYY;MBWAY|XXX-XXXXX",
"selected_method": PaymentSelected()
};
console.log("API params: ", apiParams);
// Use jQuery's $.ajax() function to make the request
$.ajax({
type: "GET",
url: apiUrl,
data: apiParams,
success: function(response) {
console.log("API response: ", response);
window.open(response.link, "_blank");
},
error: function(xhr, status, error) {
console.error("Error: ", error);
}
});
}
I am trying to consume a mercadolibre API that returns a json with some data that I need to use.
But everytime I tried by an ajax GET request it returns the same error:
"Response to preflight request doesn't pass access control check: It does not have HTTP ok status"
I Think it is a CORS issue, but I have tried everything on headers while the request (which is corssed domain) and nothing seems to work.
Here is the way I am doing the ajax request:
if (obtieneCotizaciones == 'true' && token != null) {
var sellerID = '499777238';
$.ajax({
type: "GET",
url: "https://api.mercadolibre.com/quotations?access_token="+token+"&seller.id="+sellerID+"&caller.type=seller",
contentType: "application/json",
headers: {
'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods':'GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS',
'Access-Control-Max-Age': '604800',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Headers':'application/json',
'Access-Control-Allow-Headers': 'x-requested-with'
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error)
console.log("FAIL");
}
});
}
Any Idea how could I solve this? don't mind for 'token' and 'obtieneCotizaciones' variables, they are just needed to make the request and I obtein them before doing the request.
Have you tried removing all of the headers? They are triggering a pre-flight which is why it's failing with that error.
I am trying to solve the problem of cross-domain, whenever I change my code, it never works and I think there must be something wrong with my ajax code, please check in the code, and give me some advice, thank you.
function login(url,name,password){
console.log("login");
console.log(url);
var tips = document.getElementById('tips');
$.ajax({
url: url,
type:"POST",
headers: {
"Content-Type": "application/json"
},
data:{
"user_code" : name,
"user_key" : password
},
dataType: "json",
// xhrFields: {
// withCredentials: true
// },
success:function(data){
if(data.token == undefined){
console.log(data);
tips.innerHTML = "错误";
}else{
saveToken('token',data.token,1);
saveToken('user_id',data.user_id,1);
checkToken(data.token);
}
},
error: function(msg){
console.log(msg);
console.log("fail");
}
});
}
Append in server response in header field,Below code helps you for resolving the issue,i am using below code in java.You can use any other language also.
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin");
But the same error into browser
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://abc-test123.com/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’).
My Browser supports Cors
I have an extenstion of Cors for Chrome and CorsE ad-ons for Firefox
All API's working perfectly from same domain into my localhost server but one of our project API's are not working anymore
We are working on Slim Framework here is PHP file Code
$corsOptions = array(
"origin" => "*",
"exposeHeaders" => array("X-My-Custom-Header", "X-Another-Custom-Header"),
"maxAge" => 1728000,
"allowCredentials" => True,
"allowMethods" => array(" PUT, GET, POST, DELETE, OPTIONS"),
"allowHeaders" => array("X-PINGOTHER")
);
$cors = new \CorsSlim\CorsSlim($corsOptions);
$app->add($cors);
I am calling ajax function(which was working before)
var dataString = {
username: "test",
password: "test123"
}
$.ajax({
method: "POST",
url: varURI, //My url variable
data: dataString,
crossDomain: true,
success: function(data)
{
if(data.status == "success")
{
alert("Success");
}
else
{
alert("Failure");
}
}
});
I have tried below new things after API error
//(1)
$.support.cors = true;
//(2)
$.ajax({
method: "POST",
url: varURI, //My url variable
data: dataString,
dataType: "jsonp",
async: false, //and true too
crossDomain: true,
success: function(data)
{}
});
But the same error...
I have checked many questions and applied everything then after asked question here. So need help or any require info which I am missing here.
Add following code in your .htaccess
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>
And also look on answer from this link
http://enable-cors.org/server_apache.html
I have an Ajax request on a domian xyz.com and I am performing an
Ajax request from xyz.com to pull data from abc.xyz.com
var request = $.ajax({
type: "POST",
url: "https://abc.mno.com/vending/mainvending.php",
data: {vlu:"1"},
dataType: 'json',
timeout: 10000,
crossDomain: true,
async: true,
cache: false,
headers: { "cache-control": "no-cache" },
error: function( jqXHR, textStatus, errorThrown )
{
alert("error : " + errorThrown + " text :"+textStatus + " j :" +jqXHR.status);
// alert(jqXHR.responseText);
},
success: Succeeded,
beforeSend: function( xhr ) { }
});
but I keep getting this error which is consoled out in the browser (Chrome)
XMLHttpRequest cannot load https://abc.xyz.com/vending/mainvending.php. Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight response.
In the mainvending.php the codes are as follows
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
require_once 'vendors.php';
if(!empty($_POST)){
/** Other codes follow **/
}else{
/** Other codes follow **/
}
?>
what am I not doing or what am I doing wrong? The domain name is xyz and the domain I am retrieving data from is of a sub domain could that be the issue and how do I go around this.
Your error message says that the server isn't allowing you to send a cache-control header.
You are doing that here:
headers: { "cache-control": "no-cache" },
… cache-control is a response header, so it makes no sense to include it in a request.
Remove that line.
(Alternatively, you could add it to the Access-Control-Allow-Headers header that you are already setting).
You can do one of the following two things:-
Remove this key-value pair from your AJAX config
headers: { "cache-control": "no-cache" },
Add cache-control header to your PHP code to allow it.
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, cache-control');
Try setting these headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");