I'm having a slight issue with a cross site origin request. I'm sure it is a simple fix.
Console error:
XMLHttpRequest cannot load https://subdomain.example.com/social/disqus. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.example.com' is therefore not allowed access.
js script causing the issue:
window.onload = function(){
//jQuery AJAX GET Method on Disqus Threads
$.ajax({
type: 'GET',
url: 'https://subdomain.example.com/social/disqus',
contentType: 'application/json; charset=utf-8',
success: function(threads) {
var len = Object.keys(threads.response).length
for (i = 0; i < len; i++){
if (threads.response[i].posts == 0 || threads.response[i].posts != 1) {
$('#' + threads.response[i].identifiers).html(threads.response[i].posts + " Comments ");
} else {
$('#' + threads.response[i].identifiers).html(threads.response[i].posts + " Comment ");
}
}
},
error: function() {
console.log("Aw, snap!");
}
});
};
I'm forcing redirects in Apache for both - this may be an issue, but it looks like the CORS request is being fired from a https:// valid site to another https:// valid site... url in the ajax request is definitely https.
I'm wondering if I am missing something from $.ajax ?
Related
I don't know how to fix this issue with using an API. It give me a browser error that says:
Access to XMLHttpRequest at
'file:///C:/Users/Gebruiker/Desktop/PokeMax/GET%20https://api.pokemontcg.io/v2/cards?s'
from origin 'null' has been blocked by CORS policy: Cross origin
requests are only supported for protocol schemes: http, data, chrome,
chrome-extension, chrome-untrusted, https. jquery-3.4.1.min.js:2 GET
file:///C:/Users/Gebruiker/Desktop/PokeMax/GET%20https://api.pokemontcg.io/v2/cards?s
net::ERR_FAILED
If someone knows what the issue is I would love to hear it!
code:
$(document).ready(function (e) {
$("#TheSubmitButton").on("click", function(event){
event.preventDefault();
var Pokemon = $("#search")
.val()
.trim()
console.log(Pokemon);
$.ajax({
url: "GET https://api.pokemontcg.io/v2/cards?" + Pokemon,
dataType: 'json',
method: "GET"
});
});
});
// for (var i = 0; i < response.cards.length; i++) {
// var pokemonCard = $("<img>");
// pokemonCard.attr("src", response.cards[i].imageUrlHiRes);
// $("#card-container").append(pokemonCard);
// }
With this code, before an year about i could get the file via XMLHttpsRequest.
Now this do not more work, because of the error:
Access to XMLHttpRequest at 'https://drive.google.com/uc?id=1zGxNBh-YTAXu74v855l2b_LPmLUaomqZ&export=download' from origin 'https://encrypt.pdfzorro.com' 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.
Is there a way at now, to get the file via javascript. I can not use any server solution, the file should go direct from googleDrive to the browser from the user.. without go on a server (with php e.g.) first.
function downloadFileContent(fileId){
gapi.client.request({
'path': '/drive/v2/files/' + fileId,
'method': 'GET',
callback: function ( theResponseJS, theResponseTXT ) {
var myToken = gapi.auth.getToken();
var myXHR = new XMLHttpRequest();
myXHR.open('GET', theResponseJS.downloadUrl, true );
myXHR.responseType = 'arraybuffer';
myXHR.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token );
myXHR.onreadystatechange = function( theProgressEvent ) {
if (myXHR.readyState == 4) {
// 1=connection ok, 2=Request received, 3=running, 4=terminated
if ( myXHR.status == 200 ) {
// 200=OK
cossole.log(myXHR.response);
}
}
}
myXHR.send();
}
});
}
Im trying to help a friend out with a program but my coding experience is somewhat dated (10 years give or take). Where trying to pull data from a database via their API. Im making this request via a XMLhttpRequest but im having issues even getting to the Server.
The error that occurs:
Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/jasper/api.shiftbase.com/api/rosters?min_date=2020-07-13&max_date=2020-12-31&department_id=24477
Its trying to search for the url on my own domain. But I need it to search cross domain.
The entire function:
function getRequest(){
var _request = new XMLHttpRequest();
var key = myKeyHere;
var url = "api.shiftbase.com/api/rosters?min_date=2020-07-13&max_date=2020-12-31&department_id=24477";
_request.onreadystatechange = function(event){
console.log(_request.readyState + " + " + _request.status);
if (_request.readyState == 4){
if ((_request.status >= 200 && _request.status < 300) || _request.status == 304){
alert(_request.responseText);
} else {
alert('Request was unsucceful: ' + _request.status);
}
}
};
_request.open("get", url, true);
_request.setRequestHeader("Accept", "application/JSON", false);
_request.setRequestHeader("Content-Type", "application/JSON", false);
_request.setRequestHeader("Authorization", key, false);
_request.send(null);
};
I've also read a lot about CORS and how this affects these kinds of requests cross domain, but i don't quite understand how it works and how i can work arround it.
Any help is appreciated.
First of all you need to prefix your URL with https://. This way you make a request to the external server instead of localhost. The second thing is that in your headers the application/JSON should be application/json.
Also dont forget that your key needs to be prefixed with "API". Example API [some_random_key]
I've tested the following code and it worked. You just have to add your own API KEY.
function getRequest(){
var _request = new XMLHttpRequest();
var key = "API [replace_this_with_your_key]"; // Example: "API a1b2c3d4e5f6g7h8i9"
var url = "https://api.shiftbase.com/api/rosters?min_date=2020-07-13&max_date=2020-12-31&department_id=24477";
_request.onreadystatechange = function(event){
console.log(_request.readyState + " + " + _request.status);
if (_request.readyState == 4){
if ((_request.status >= 200 && _request.status < 300) || _request.status == 304){
alert(_request.responseText);
} else {
alert('Request was unsucceful: ' + _request.status);
}
}
};
_request.open("get", url, true);
_request.setRequestHeader("Accept", "application/json", false);
_request.setRequestHeader("Content-Type", "application/json", false);
_request.setRequestHeader("Authorization", key, false);
_request.send(null);
};
Try to add // at the start of the line in url variable declaration (line 4), if you want to make a request to the external server.
Your request was made to the local webserver http://localhost/jasper/... and you've received a 404 (not found) error.
I'm trying to call Geocoding API but I'm not having any luck. I keep receiving the following error.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.mapbox.com/gecoding/v5/mapbox.places/fort%20coll…7nugng&autocomplete=true&bbox=-105.214,40.451,-104.85,40.841. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
When I add the header it says it can't run the script. Not sure what else to do. My link is formated properly because it works in mapbox search-Playground
var searchId = document.getElementById('mySearch');
searchId.addEventListener('keyup', function onEvent(e) {
if (e.keyCode === 13) {
console.log(searchId.value)
var urlBase = 'https://api.mapbox.com/gecoding/v5/mapbox.places/';
var location = searchId.value;
var bbox = [-105.214, 40.451, -104.850, 40.841]
var query = urlBase + location + '.json?access_token=' + mapboxgl.accessToken + '&autocomplete=true&bbox=' + bbox;
$.ajax({
method: 'GET',
url: query,
success: function(data){
console.log(data)
}
})
}
});
After long research and debugging i realized java-script was not the problem, I was rather having a cross origin resource exception which was thrown because some how the ajax request could not read my server script or rather did not have permission to access my server script.
So i tried the following codes below but still the same issue, I placed the issue in red block blow, my java script is also below and my server script
$('#send').on('click', function(e) {
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
alert("sending " + name + email + message);// this part is now working fine
$.ajax({
type: "POST",
url: "https://xxxxxx/xxxxx/php/contact/maincontact.php",
data: {
nme: name,
ema: email,
msg: message
},
dataType: 'json',
timeout: 10000,
async: true,
cache: true,// I removed the header which used to here before
error: function(jqXHR, textStatus, errorThrown) {
alert("error : " + errorThrown + " text :" + textStatus + " j :" + jqXHR.status);
alert(jqXHR.responseText);
},
success: Succeeded
});
});
function Succeeded(result) {
alert("Successing");
var data = JSON.parse(result[0]);
try {
$('#name').val(" ");
$('#email').val(" ");
$('#message').val(" ");
if (data == true) {
alert("We will Contact you shortly");
} else {
alert("OOpps! something went wrong");
}
} catch (e) {
alert("You may not enter " + e);
}
}
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxxxxx/xxxxxx/php/contact/maincontact.php. (Reason: missing token 'access-control-allow-origin' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
<!-- php codes -->
<?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('contact.php');
if(!empty($_POST)){
$addcase = new contact();
$data['vlu'] = $addcase->add($_POST['nme'], $_POST['ema'], $_POST['msg']);
echo json_encode($data);
}else{
echo "Not properly parsed";
}
?>
The error message says:
missing token 'access-control-allow-origin' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel
So when you make the request you are trying to put access-control-allow-origin in the headers. (The message means that browser is asking the server if it is allowed to send that header in cross-origin Ajax and the server isn't saying that it is OK to do that).
This doesn't make any sense. Access-Control-Allow-Origin is a response header. There is no reason to put it on the request.
Now, the code you've provided doesn't try to set that header. This suggests that elsewhere in your code you are trying to set it universally (probably via ajaxsetup).
You need to find the point where you try to set it and remove that code.