Getting error while calling a remote web API - javascript

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.

Related

Cross-domain POST doesn't work with Angular HttpClient but works with jQuery

I am migrating to Angular 13 and I want to use HttpClient instead of jQuery.ajax.
The following jquery code works:
function asyncAjax(url: any){
return new Promise(function(resolve, reject) {
$.ajax({
type: 'POST',
crossDomain: true,
xhrFields: {
withCredentials: true
},
url: url,
data: null,
contentType: "text/plain; charset=utf-8",
dataType: "json",
success: function(data) {
resolve(data) // Resolve promise and when success
},
error: function(err) {
reject(err) // Reject the promise and go to catch()
}
});
});
}
...
const json: any = await asyncAjax(url);
However, when I do with HttpClient:
private readonly _httpClient: HttpClient;
constructor(httpClient: HttpClient) {
this._httpClient = httpClient;
}
...
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
const json = await firstValueFrom(this._httpClient.post<T[]>(url, null,
{ headers: headers, withCredentials: true}));
I get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url]. (Reason: CORS request external redirect not allowed).
Could anyone say how to make it work with HttpClient?
In your jQuery code you are sending no data at all and claiming you are sending plain text.
data: null,
contentType: "text/plain; charset=utf-8",
In your Angular code you still aren't sending any data, but this time you are claiming you are sending JSON.
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
JSON isn't a data type supported by HTML forms which means to send it on a cross-origin request the browser will send a preflight request.
The server isn't granting permission using CORS in its response to that preflight request and seems to be issuing a redirect instead.
The quick and dirty solution here is to send the same Content-Type header as you were when the code worked.
The better solution is to consider your API design. Why are you using a POST request but not POSTing any data in the first place? Possibly this should be a GET or DELETE request instead.
It is also possible that the cause of the redirect is that the value of url has changed (maybe from http://example.com/foo/ to http://example.com/foo) and that needs to be corrected.

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);
}
});

How to call web API with GET method basic authentication into jquery() in javascript

Hello I am using this method to read this api it giving CORS error. I have added CORS plugin with chrome then also it is not coming. Please let me know how to solve these to error.
text:
function NoCors() {
debugger;
var uName = "*****";
var passwrd = "*****";
document.write("Enter1");
var url = 'http://219.90.67.163:8207/api/Info/getgismeterdata'
$.ajax({
type: 'GET',
url: url,
crossDomain: true,
//Access-Control-Allow-Credentials: true,
contentType: 'json',
datatype: "application/json",
headers: {
"Authorization": "Basic QXBpVXNlcjpBcGlQYXNz",
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName + ":" + passwrd));
},
success: function (data) {
debugger;
console.log("data")
//Success block
},
error: function (xhr, ajaxOptions, throwError) {
//Error block
},
});
}
error in console:
1. Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
2. Access to XMLHttpRequest at 'http://219.90.67.163:8207/api/Info/getgismeterdata' from origin 'http://localhost:50362' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Before sending the GET request to server, browser automatically send and preflight OPTIONS request, and your server doesn't allow this method. You need to enable OPTIONS method support in your server side (219.90.67.163)
Are you use Bearer Token Authentication?
requst headers try this
headers: {
"Authorization": "Bearer QXBpVXNlcjpBcGlQYXNz",
},
You must setting CORS in Web API
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
The CORS plugin you are using only works for Simple Requests.
Since you are setting an Authorization header you are making a Preflighted Request which your plugin cannot handle.
You need a different approach to handling the Same Origin Policy. Ideally, that would be proper support for CORS on the server you are making the HTTP request to but some other options are listed at the end of this answer.

jQuery/Ajax Rest api request

I'm trying to make an rest api request to realla https://realla.co/api/#/ from localhost, I have an api key and can make the request via PHP but having issues using ajax:
var URL = "https://realla.co/api/v1/listings/search";
var usr = 'api';
var psw = 'hidden';
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: URL,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(usr + ":" + psw))
},
success: function(result) {
console.log('success');
},
error: function(req, status, err) {
console.log('Something went wrong', status, err);
}
});
Returns the error
XMLHttpRequest cannot load https://realla.co/api/v1/listings/search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://dw.dev' is therefore not allowed access. The response had HTTP status code 403.
I tried to fix that problem with https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en but still get the same message.
I've added the following function (running Wordpress):
/*
* Modify HTTP header
*/
function new_headers($headers) {
if (!is_admin()) {
$headers['Access-Control-Allow-Origin'] = '*';
$headers['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS';
$headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, X-Auth-Token';
}
return $headers;
}
add_filter('wp_headers', 'new_headers');
I've tried other APIs (Facebook) and that works but I wonder if I'm missing something with this.
The documentation for Realla is pretty thin, but I wonder if I'm doing something wrong.
Thanks
let's try this
it will work
Add header in requested resource file
<?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');
?>
Issue was realla's side. The API prevents requests being made via ajax.
In order to use the API, you are required to make requests from the server rather than the clients browser.
Sorry to waste people's time, hopefully this answer will help anyone else who feels like they're banging their head against a brick wall.

cross-origin resource sharing (CORS) with jQuery and Tornado

Let's say, I have a Tornado web server (localhost) and a web page (othermachine.com), and the latter contains javascript that needs to make cross-domain ajax calls to the Tornado server.
So I set up my Tornado as such:
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "http://www.othermachine.com")
self.set_header("Access-Control-Allow-Credentials", "true")
self.set_header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
self.set_header("Access-Control-Allow-Headers",
"Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, Cache-Control")
And my javascript makes a jQuery call:
$.ajax({
type: 'GET',
url: "http://localhost:8899/load/space",
data: { src: "dH8b" },
success: function(resp){
console.log("ajax response: "+resp);
},
dataType: 'json',
beforeSend: function ( xhr ) {
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.setRequestHeader('Access-Control-Request-Method', 'GET');
xhr.setRequestHeader('Access-Control-Request-Headers', 'X-Requested-With');
xhr.withCredentials = true;
}
});
But I get the lovely XMLHttpRequest cannot load http://localhost:8899/load/space?src=dH8b. Origin http://www.othermachine.com is not allowed by Access-Control-Allow-Origin error. I can't tell which side of jQuery / Tornado (or both?) am I not setting up correctly.
According to dev tools, these are the headers the jQuery request is sending:
Request Headers
Accept:*/*
Origin:http://www.othermachine.com
Referer:http://www.othermachine.com/athletes.html?src=BCYQ&msgid=6xjb
User-Agent:Mozilla/5.0 ...
If I simply make a request from my browser's url field I get a '200 OK' with this:
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, User-Agent, X-Requested-With, X-Requested-By, Cache-Control
Access-Control-Allow-Methods:GET,POST
Access-Control-Allow-Origin:http://www.othermachine.com
Content-Length:0
Content-Type:text/html; charset=UTF-8
Server:TornadoServer/2.2.1
Does that mean Tornado is doing its job? I tried to follow the advice of all the stackoverflow CORS+jQuery posts (e.g. this), to no avail. CORS in concept seems simple enough, but maybe I am fundamentally misunderstanding what is supposed to happen in a CORS transaction... please help! Thanks in advance.
Nevermind, coding too late and too long causes one to trip over things the size of typos. For the record, this is all you need for jQuery:
var data = { msgid: "dH8b" },
url = "http://localhost:8899/load" + '?' + $.param(data);
$.getJSON( url, function(resp){
console.log("ajax response: "+resp+" json="+JSON.stringify(resp));
});
And this is all you need for Tornado:
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "http://www.othermachine.com")
Using jQuery 1.7.2, Tornado 2.2.1.
try setting origin to be: othermachine.com. it should be a domain name, not a website address

Categories

Resources