Microsoft Cognitive Services JavaScript Request 'Access-Control-Allow-Origin' - javascript

Hy, when I try to access the Microsoft Cognitive Services API via JavaScript from my server/local machine I get the following error.
XMLHttpRequest cannot load http://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myUrl.com' is therefore not allowed access. The response had HTTP status code 401.
This is my request code:
function requestAPI(){
var params = {
// Request parameters
"visualFeatures": "Categories"
};
$.ajax({
url: "http://api.projectoxford.ai/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{myKey}");
},
type: "POST",
// Request body
data: "{'url':'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
}
In my .htaccess I already added:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
When I test the request with hurl.it it works. Just from my server it doesn't.

Looks like you are setting CORS headers for your server which means someone can make cross-domain request to your server.
Microsoft Cognitive Services have to add these headers on their server so that you can make cross-domain request to them or you have to use JSONP.

Related

I want a post request from javascript to php across different domain. CORS error, header origin error

So I have an ajax request:
$.ajax({
url: "some url different domain/transfer.php",
headers: {
"Access-Control-Allow-Origin": "*",
},
type: "post",
dataType: "json",
success: function (msg) {
console.info(msg);
gfg = msg;
console.log(gfg);
},
});
and this is the header of my transfer.php file-
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
So after working for more than 2 days I am having an error:
Access to XMLHttpRequest at 'some URL different domain/transfer.php' from origin 'http://localhost' 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.
I have tried also tried "jsonp" instead of JSON type but in that case, it gives me an error: "<? unidentified token in 1st line"
which is obviously necessary for PHP.
Pleaseeeeee anyone on this planet can help me to make a post/get request using js to PHP (I am receiving an array from PHP). Before I burn my laptop :) Thanks!
Add on your server
Access-Control-Allow-Origin: *

Getting Error while calling external api end point using javascript

I am new to JavaScript and i am trying to send api request from JavaScript.
I am getting below error while calling external endpoint from JavaScript.
from origin 'null' has been blocked by CORS policy: Request header field x-api-key is not allowed by Access-Control-Allow-Headers in preflight response.
var url = "<external_api_for_graphQl"
var api_key = "<api_key>"
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader("x-api-key", api_key);
xhr.send("");
alert(xhr.status);
any idea how we can resolve this?
Thanks
try to set header
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
The Access-Control-Allow-Headers header is sent by the server to let the client know which headers it supports for CORS requests. The value of Access-Control-Allow-Headers should be a comma-delineated list of header names, such as "X-Custom-Information" or any of the standard but non-basic header names (which are always allowed).
This error occurs when attempting to preflight a header that is not expressly allowed (that is, it's not included in the list specified by the Access-Control-Allow-Headers header sent by the server). To fix this, the server needs to be updated so that it allows the indicated header, or you need to avoid using that header.
one think you can try is this:
$.ajax({
headers: { "Accept": "application/json", "x-api-key":"<x-api-key>"},
type: 'POST',
url: '<external_api_for_graphQl>',
crossDomain: true,
beforeSend: function(xhr){
xhr.withCredentials = true;
},
success: function(data, textStatus, request){
console.log(data);
}
});

No 'Access-Control-Allow-Origin' header is present on the requested resource error after adding Access-Control-Allow-Origin

I want to get json from a firebase cloud function.
So the json url works on browser and my android app. But when i try it on my javascript code it doesn't show anything.
And gives me an error
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
In Node JS
this is my code to send response,
res.set('Access-Control-Allow-Origin', "*");
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.status(200).send(JSON.stringify(datacompletearrayPaged));
and on client side ,
I use the following code to get json
$.get(url, (r) => console.log(r))
You need to include the crossDomain: true property in your request.
You can't provide options to $.get(), so you'll need to use $.ajax() instead:
$.ajax({ url, crossDomain: true }, r => console.log(r));

CORS issue with Keyrock

I'm trying to integrate a custom application with Keyrock Fiware Identity Manager.
The flow is the following:
The user clicks on LOGIN button
He is redirected to the
/oauth2/authorize/?response_type=code&client_id={clientid}&state=xyz&redirect_uri=http:{ip}:{port}
The user inserts his credentials
After the authentication he is redirected to my application where I try to retrieve the token as follow:
var reqData = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + http:{ip}:{port};
var reqHeaders = new Object();
reqHeaders.Access-Control-Allow-Headers= "Content-Type, Access-Control-Allow-Headers,Access-Control-Allow-Origin, Authorization, X-Requested-With, origin, accept",
reqHeaders.Access-Control-Allow-Methods= "POST, GET, OPTIONS, DELETE, PUT",
reqHeaders.Access-Control-Allow-Origin="*"
reqHeaders.Access-Control-Expose-Headers="http://*/*"
reqHeaders.Authorization="Basic {token}"
reqHeaders.Content-Type="application/x-www-form-urlencoded"
reqHeaders.X-Requested-With="XMLHttpRequest"
$.ajax({
url : idmURL + '/oauth2/token',
type : 'POST',
dataType : 'json',
crossDomain : true,
data : reqData,
headers : reqHeaders,
success : function(data) {
console.log(data);
token = data.access_token;
}
});
But the post request never starts because I receive:
XMLHttpRequest cannot load http://{ip}:{port}/oauth2/token. Request header field Access-Control-Allow-Methods is not allowed by Access-Control-Allow-Headers in preflight response.
I've tried to insert the {ip}:{port} to the CORS_WHITELIST and to the ALLOWED_HOST in the local_settings.py file of Keyrock, but nothing changes.
Anyone can help me?
Ironically, I think the issue is caused by the fact that you're using the CORS headers meant for responses in your request:
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Allow-Origin
Access-Control-Expose-Headers
Thus the preflight fails because the server does not allow these, only a subset of headers as provided in the response header Access-Control-Allow-Headers.
Remove these from the request.
For more info: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Request header field Access-Control-Request-Methods is not allowed by Access-Control-Allow-Headers in preflight response

I'm trying to send a POST request from my website to my remote server but I encounter some CORS issues.
I searched in the internet but didn't find a solution to my specific problem.
This is my ajax request params:
var params = {
url: url,
method: 'POST',
data: JSON.stringify(data),
contentType: 'json',
headers: {
'Access-Control-Request-Origin': '*',
'Access-Control-Request-Methods': 'POST'
}
On the backend side in this is my code in python:
#app.route(SETTINGS_NAMESPACE + '/<string:product_name>', methods=['POST', 'OPTIONS'])
#graphs.time_method()
def get_settings(product_name):
settings_data = helper.param_validate_and_extract(request, None, required=True, type=dict, post_data=True)
settings_data = json.dumps(settings_data)
response = self._get_settings(product_name, settings_data)
return output_json(response, requests.codes.ok, headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'
})
I get an error on my console:
XMLHttpRequest cannot load [http://path-to-my-server]. Request header field
Access-Control-Request-Methods is not allowed by
Access-Control-Allow-Headers in preflight response
I did notice that I can add also 'Access-Control-Request-Headers' but I wasn't sure if it necessary and it cause me more problems so I removed it.
Does anyone know how to solve this problem?
Your ajax request shouldn't send Access-Control headers, only the server sends those headers to allow the servers to describe the set of origins that are permitted to read that information using a web browser.
The same-origin policy generally doesn't apply outside browsers, so the server has to send CORS headers or JSONP data if the browser is going to be able to get the data.
The browser doesn't send those headers to the server, it doesn't have to, it's the server that decides whether or not the data is available to a specific origin.
Remove the header option from the params object, and it should work

Categories

Resources