This question already has answers here:
CORS error when jquery ajax request on api
(2 answers)
Closed 5 years ago.
I have here a strange situation with AJAX call, how to pass api key in header:
My full url for my json is: https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&APIkey=fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0
And I am trying now to pass API key in headers of ajax call, but still have this error from console:
"Failed to load https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://bigsportlive.com' is therefore not allowed access."
Here is my ajax call:
var apiKey = "fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0";
$.ajax({
type: "GET",
url: "https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01",
headers: { "APIkey": apiKey },
success: function(result){
result[i].league_name
}
});
May be I am doing something not correct?
Thanks!
If you want to add a header (or a set of headers) to each request, use the beforeSend hook with $.ajaxSetup ():
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your custom header
$.ajax({ url: 'your/url' });
// Sends both custom headers
$.ajax({ url: 'your/url', headers: { 'x-some-other-header': 'some value' } });
Another solution consist to use lowercase for headers
$(document).ready(function () {
$.ajax({
url: "http://xx.xx.xx.xx:xx/api/values",
type: "GET",
dataType: "json",
headers: { "HeaderName": "MYKey" }
});
});
Yes, there is an Access-Control-Allow-Origin error.
If so, you may want a php backend to get this for you, I believe, using
<?php
$data = file_get_contents("https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&APIkey=fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0");
echo json_encode($data);
?>
Then use an ajax call to this file.
$.ajax({
type: "GET",
url: 'name_of_php_file.php',
dataType: "json",
success: function(result){
alert(result);
}
});
Related
I am a problem with simple javascript web page hosted on AWS S3 that makes a HTTP POST to AWS API Gateway using ajax.
I am able to make a call using curl with success:
curl -X POST -H "Content-Type: application/json" https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta --data #data.json
data.json file:
{ "imie": "jasiu",
"ocena": "6",
"opinia": "niezle"
}
My javascript code looks like this.
<html>
<body>
<title>Ankieta</title>
<h1>Wypelnik ankiete</h1>
<button type="button" onclick="uruchom()">JSON</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function uruchom() {
var resultDiv = $("#resultDivContainer");
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: JSON.stringify(myData),
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
};
</script>
</body>
</html>
This is the error I get from web debug:
GET https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta?callback=jQuery17203000220305941388_1546897907447&{%22imie%22:%22Michal%22}&_=1546897908872 net::ERR_ABORTED 400
It looks like there is problem with callback and in the URL is altered with my data from body. In my case I don't want to check whenever the callback is fine - want to simply POST data.
Thanks for any suggestions.
POST can't be used to send a JSONP request. JSONP doesn't actually use AJAX, it works by creating a <script> tag whose src is the URL. There's no way to send POST data this way, so the data is added as URL parameters.
If this API expects the JSON in POST data, you can't use dataType: 'jsonp'. You have to use dataType: 'json'. If the API doesn't allow CORS, you'll need to use a proxy on your server to make the actual request, you can't do it directly from the browser.
Dont stringify the data object. JQuery does this for you. Just pass object.
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: myData,
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
Thanks for suggestions and answers especially in CORS direction. I was sure my API GW has CORS enabled, but didn't check AWS Lambda that is behind it and found that I was not returning "Access-Control-Allow-Origin" header back to client.
exports.handler = function(event, context, callback) {
callback(null, {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
}
});
};
After applying this, I can send HTTP POST.
I'm trying to login to moodle from an external webpage using a post form to moodle, I used the next ajax to send the inputs:
var frm = $('#loginForm');
frm.submit(function(e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
xhrFields:{
withCredentials:true
},
async:true,
beforeSend: function (xhr){
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data) {
console.log("Logged");
},
error: function (data) {
console.log("NOT Logged");
},
});
});
Now into the moodle's login/index.php I insert the headers to make possible the CORS connection:
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://fabianmurillo.000webhostapp.com");
header("Origin" : "http://fabianmurillo.000webhostapp.com");
When I run the code, the browser returns an error:
..preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'..
enter image description here
Dunno why browser is blocking the connection for login to moodle.
Thanks for your help.
I'm trying to send a post request using ajax but I keep getting the following error :
XMLHttpRequest cannot load http://192.168.1.123:8080. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
here is my code
$.ajax({
type: "POST",
url: "http://192.168.1.123:8080",
data: JSON.stringify([{"VisitorName ": " "+document.getElementById("VisitorName ").value}
]),
contentType: "application / json ",
crossDomain: true,
dataType: "json",
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
$.ajax({
type: "POST",
url: "http://192.168.1.123:8080,
data: JSON.stringify([
{
"
VisitorName ": "
"+document.getElementById("
VisitorName ").value,
}
From what I can tell the comma next to value is causing a syntax error. Also within the code you do not close the " for "http://192.168.1.123:8080
I got an url let’s say abc its type is post. if I try to call it as $.ajax method post it is showing method not allowed 405 error. it I sent by method get it is working fine but the business is not done how to solve the issue?
js code:
$.ajax({
type: "POST",
url: url,
data: data,
beforeSend: function (request){
request.setRequestHeader("X-CSRF-TOKEN", token)
},
success: function(res){
console.log(res)
},
error: function(){
JSON.parse(this.error.arguments[0].responseText).error.message.value
},
dataType: "json"
});
You should use 'method' instead of 'type'. Try this:
$.ajax({
method: "POST",
url: url,
data: data,
beforeSend: function (request){
request.setRequestHeader("X-CSRF-TOKEN", token)
},
success: function(res){
console.log(res)
},
error: function(){
JSON.parse(this.error.arguments[0].responseText).error.message.value
},
dataType: "json"
});
Or you can use the jQuery.post method.
405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource. 405 Method Not Allowed
I am trying to use this API: https://zipcodedistanceapi.redline13.com/API
But when I make the AJAX call, I'm getting this error:
XMLHttpRequest cannot load
https://zipcodedistanceapi.redline13.com/rest//radius.json/30341/10/mile.
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Here is the request:
$.ajax({
type: "GET",
url: 'https://zipcodedistanceapi.redline13.com/rest/<api key goes here...>/radius.json/30341/10/mile',
dataType: "json",
success: function(zipback) {
}
});
I know it has something to do with making the request from a different domain, but I don't not how to resolve the issue.
$.ajax({
type: "GET",
url: 'https://zipcodedistanceapi.redline13.com/rest/<api key goes here...>/radius.json/30341/10/mile',
dataType: "json",
jsonpCallback:'somename',
success: function(zipback) {
}
});