Unable to make ajax request to remote server from localhost - javascript

I am making an ajax request (with jquery) from my local server to a remote page (which I am the admin) and I get
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ica.local.com' is therefore not allowed access. The response had HTTP status code 405.
This is how my request looks like:
$.ajax({
url: myurl,
type: "POST",
// This is the important part
xhrFields: {
withCredentials: true
},
// This is the important part
success: function (response) {
// handle the response
},
error: function (xhr, status) {
// handle errors
}
});
The application on the remote server is running on nginx server. I tried to change the conf file of nginx to Access-Control-Allow-Origin: * but it still doesnt work.

It is because both the machines are on different servers. For development purpose you can use chrome extensions already available to fix the purpose.
Just search 'Cross origin issue' on chrome extension page and then include one of extensions

Try to create a sample server file like php and call the remote with curl from php.
Than return the response as json to your is

Related

Send Ajax Request For Sending Post Data One Url to Another Url Without Getting CROS ERROR

-> Please Help Me To Solve The Problem
-> I Send Data To Another URL for Process Something And That Web Page is another Server and Different URL.
-> When Ever I Try To Send Post Data That time i Faced CROS Error i try many ways.
-> See My Code
$.ajax({
type: 'POST',
url: 'Another Non Https Url',
crossDomain: true,
contentType:'application/json',
data:{CompanyEmail:CompanyEmail,CompanyName:CompanyName,CompanyPhoneNumber:CompanyPhoneNumber,AccessToken:AccessToken},
success: function(){
alert("Success");
},
error: function(){
alert("Failed");
}
})
CORS (meaning "Cross Origin Resource Sharing") is a server-side mechanism to allow exceptions in the so-called Same-Origin-Policy. Otherwise processing data from another origin is prevented.
You have to explicitly enable CORS for your client within your server.
This can't be fixed in your client-side jQuery-Code.
PHP-side you are able to activate CORS for all clients by using
<?php
header("Access-Control-Allow-Origin: *");
?>
though.

Is it possible to make a cross origin request to a web page where I have no control?

Im trying to make a an Ajax call to https://www.treasury.gov/ofac/downloads/sanctions/1.0/sdn_advanced.xml but I keep getting No 'Access-Control-Allow-Origin' header is present on the requested resource.
Considering I have absolutely no control over the source of this information is this request actually possible? Do I just need the right configuration for my request or is this physically impossible?
$.ajax({
url: 'https://www.treasury.gov/ofac/downloads/sanctions/1.0/sdn_advanced.xml',
type: "GET",
crossDomain: true,
dataType: "xml",
success: function (response) {
console.log(response)
},
error: function (xhr, status) {
alert("error");
}
});
It is not possible as you have no access to source API and source may not have CORS enabled.
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. It is required that CORS is enabled for the source file. You can check more here regarding same origin policy.: https://developer.chrome.com/extensions/xhr

Cannot 'GET' mLab Data b/c of CORS

I can't execute the 'GET' request with the getTasks() function.
$(document).ready(function(){
getTasks();
});
const apiKey = 'xxxxxxx';
function getTasks(){
$.ajax({
type: 'GET',
url: 'https://api.mlab.com/api/1/databases/taskmanager/collections/tasks?apiKey='+apiKey,
contentType: 'application/json',
xhrFields: {
withCredentials: true
},
success: function(data){
console.log(data);
},
error: function(){
console.log('FAIL')
}
})
}
The error that I get is:
api.mlab.com/api/1/databases/taskmanager/collections/tasks?apiKey=xxxxxxx
Failed to load resource: the server responded with a status of 400
(Bad Request)​
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access. The response
had HTTP status code 400.
I understand that Google-Chrome on Windows is CORS enabled, and will not (by default) allow communication with a different domain. I'm not sure what a preflight request is. Regardless, I tried to implement what I saw from Using CORS - HTML5 Rocks​ (from the CORS from jQuery section), but to no avail.
At a guess, the remote API simply does not respond to pre-flight requests for GET calls (because it shouldn't have to).
Your code is triggering a pre-flight request because it is non-simple. This is due to your adding a Content-type: application/json header. A request Content-type header is used to indicate the request payload format. As it is a GET, there is no payload.
Try this instead...
$.getJSON('https://api.mlab.com/api/1/databases/taskmanager/collections/tasks', {
apiKey: apiKey
}).done(function(data) {
console.log(data)
}).fail(function() {
console.log('FAIL')
})
CORS is there to protect you. If you want some more info on it, wikipedia has a good entry on it.
It appears the issue here is that you're trying to access your mongodb hosted by mlab directly from your web app. As you can see in your code, you're providing credentials/api keys to make that request.
My guess is that mlab's intent of not allowing CORS is to prevent you from doing this. You should never put your private API keys in html to be hosted on a web page, as it's easily accessible by reading source code. Then someone would have direct access to your mongodb.
Instead, you should create a server-side application (node, or... ** Whatever **) that exposes an api you control on the same domain (or a domain you give permission to via CORS).
As far as the "preflight" request, if you look in your chrome debugging tools, you should see an additional request go out with the "OPTIONS" method. This is the request that chrome (and most other http clients) send out first to a server hosted on a different domain. it's looking for the Access-Control-Allow-Origin header to find out whether it's allowed to make the request. Pretty interesting stuff if you ever have some time to dig into it.

CORS error when jquery ajax request on api

I am using jQuery ajax to send request to some API. Due to the CORS policy I got a CORS error on the browser's console
Here's by code
$.ajax({
url: sendHere,//api url
type: 'GET',
contentType: 'text/plain',
crossDomain: true,
beforeSend: function(xhr){
xhr.withCredentials = true;
},
}).done(function (result) {
console.log(result);
}).error(function (err) {
//console.log(err);
});
Error
'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.mywebsite.com' is therefore not allowed access.
I tried to solve this problem by installing a chrome extension to enable allow cross origin request. This extension somehow solved my problem and got a response from the api. But installing an extension is not good.
I also tried to make the request with JSONP(dataType:'jsonp') but the response given by the api is not in json format, it is string so it gives an error.
Code with JSONP
$.ajax({
url: sendHere,//api url
type: 'GET',
crossDomain: true,
dataType:'jsonp',
}).done(function (result) {
console.log(result);
}).error(function (err) {
//console.log(err);
});
Uncaught ReferenceError: E0002 is not defined
where "E0002" is the response string from the api
!!!PLEASE HELP!!!
There are 2 situations -
If you have control over the api code then
make changes in header and add your origin as well.
If you don't have control to change CORS header that is coming from
the api
you have only one option create a backend code(your own api) in any language you prefer that make an http request and get the data. now use your own api to get data on your frontend.
The cors error is cross origin request policy maintained by the browser for security.
To solve your problem either you will have to allow cors request in your server coding or if you do not have access to the server api code you will have to make the api call from your server to api server

Error Cross Domain calling Json

I'm trying to bring my json file into my HTML but a error Cross Domain is happening:
XMLHttpRequest cannot load http://guardioesdacidadania.com.br/game_temp/assets/js/caratulas.json?jsoncallback=. The request was redirected to 'http://www.guardioesdacidadania.com.br/game_temp/assets/js/caratulas.json?jsoncallback=', which is disallowed for cross-origin requests that require preflight.
I've tried many different solutions but none of them worked.
Here's my js code.
$.ajax({
url: 'http://guardioesdacidadania.com.br/game_temp/assets/js/caratulas.json?jsoncallback=',
headers: { 'Access-Control-Allow-Origin': '*' },
crossDomain: true,
success: function () { alert('it works') },
error: function() {alert('it doesnt work')},
datatype: 'jsonp'
});
For CORS support to work, the server must be configured to respond with the Access-Control-Allow-Origin header, sending the header with your request does nothing. You can see a bit of information on how to get this to work by visiting : Origin is not allowed by Access-Control-Allow-Origin
If you do not have access to the server, then it is not possible to do it via AJAX so you'll need to create some sort of server side proxy to relay the request through.

Categories

Resources