does it?
Everything is working fine, until I send the user response to the google server to verify. This is the code that sends the response:
$http({
method: "get",
url: "https://www.google.com/recaptcha/api/siteverify",
params: {
secret: 'my-secret-key',
response: $scope.response
}
}).success(function (response) {
console.log(response);
}).error(function (errResponse) {
console.log(errResponse)
});
Then, I am getting this:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
Yes it works, but you can't send ajax/http requests to validate captcha from js. Yous should write your own backend function which will send this request.
Something like this:
Getting response from captcha with js callback (as you already did)
Send ajax request with captcha response to your own server
From your server send request with response and secret key to https://www.google.com/recaptcha/api/siteverify
Return response to your ajax function.
Related
I am trying to access linkedin profile using axios get request, which doesn't work on localhost and I get the following error
XMLHttpRequest cannot load
https://api.linkedin.com/v1/people/~:(id,email-address)?format=json.
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:8030' is therefore not allowed
access. The response had HTTP status code 401.
I am able to get access-token using react-linkedin-login package, after getting the access token I am trying the following code
var linkedInUrl = `https://api.linkedin.com/v1/people/~:(id,email-address)?format=json`;
var headers = {
'Authorization': `Bearer ${accessToken}`,
'Access-Control-Allow-Methods':'GET,PUT,PATCH,POST,DELETE',
'Access-Control-Allow-Origin':'*',
'Access-Control-Request-Headers':'Origin, X-Requested-With, Content-Type, Accept',
'Content-Type':'application/x-www-form-urlencoded'
};
return (dispatch) => {
axios.get(linkedInUrl, {headers}).then(({data}) => {
console.log(data);
}, (error) => {
console.log(error);
});
}
The problems lies in linkedin server how it takes request I guess, it doesn't allow localhost to make call I think. How to overcome this to actually develop the service before I deploy and run on server.
Thanks for helping..
This is because of a browser restriction called the "Same-origin Policy", which prevents fetching data from, or posting data to, URLs that are part of other domains. You can get around it if the other domain supports Cross-origin Resource Sharing (CORS), but it looks like LinkedIn doesn't, so you may have trouble.
One way around this is to have a web service which can proxy your request to LinkedIn - there's no domain restrictions there.
https://en.wikipedia.org/wiki/Same-origin_policy
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
try jsonp for CORS request - reference - axios cookbook
var jsonp = require('jsonp');
jsonp(linkedInUrl, null, function (err, data) {
if (err) {
console.error(err.message);
} else {
console.log(data);
}
});
EDIT
Use jQuery to perform JSONP request and to set headers
$.ajax({url: linkedInUrl,
type: 'GET',
contentType: "application/json",
headers: header, /* pass your header object */
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log('Error', err);
},
});
https://cors-anywhere.herokuapp.com/ - Add this before the url and it will work
This is pretty much a known standard error but unable to fix the same using existing Stackoverflow posts.
XMLHttpRequest cannot load https://myserver.com/context/
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.otherwebsite.com' is therefore not allowed access.
The response had HTTP status code 405.
Following is the code I have -
function setHeader(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
}
var url = "https://myserver.com/context/";
$.ajax({
url: url,
type: 'GET', dataType:'json',
success: function(data) {
_this.question(data.question);
_this.questionId(data.questionId);
_this.choices(data.choices);
}, error: function() {
console.log("ERROR in getting microquestion");
},
beforeSend: setHeader
});
The “Response to preflight request… had HTTP status code 405.” message indicates, to start, the https://myserver.com/context/ endpoint needs to be configured to handle OPTIONS requests correctly—even if it may already be set to send the right CORS headers back for “normal” requests.
For more details about what’s happening, you can read the How to avoid the CORS preflight section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API — but the gist of it is, minimally, the server must respond to OPTIONS requests with a 2xx success status code.
I'm trying to get a response from server. The function looks so:
function getOverview() {
var req = {
method: 'GET',
url: base,
headers: {
'authorization': 'Bearer ' + GottenTokens.getSessionToken()
}
};
return $http(req).then(
function successCallback(response) {
return response;
}, function errorCallback(response) {
console.log(response);
return response;
});
}
When the status is 200, there's no problem, it returns the good response with status 200. But... when the status is 401, than it returns a response with status -1:
Object {data: null, status: -1, config: Object, statusText: ""}
I was trying it in postman and I saw there's the status 401 and also in browser it says so:
XMLHttpRequest cannot load http://localhost:5000/overview. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.
It means that the browser and postman take the status from server, but it doesn't come in Angularjs. I was trying this post: Capture Http 401 but it doesn't help me. I have that function in a "factory".
By the way, the server is written in akka. I don't know if it has something to do. Before was it in NodeJS and I didn't have problems. Since it's in akka I can't get the status in Angularjs.
Could anybody help me?
When doing cross-site requests, the server has to add to ALL responses a valid CORS header. This includes error responses like 401.
Make sure you can see the "Access-Control-Allow-Origin" header in your 401 response, it's most likely missing.
I am sending data in json format from javascript using XMLHttpRequest and receiving data at node.js file as following
client.js
$.ajax({
type: "POST",
dataType: 'json',
data: JSON.stringify(Idata),
url: AjaxURL,
success: function (result) {
return true;
}
});
server.js
var http = require('http');
console.log("server initialized");
var server = http.createServer(function (req, response) {
req.on('data', function (data) {
var d = JSON.parse(data);
console.log("data : " + d.OperationType);
});
req.on('end', function () {
response.end();
});
}).listen(3000);
Now i successfully got the value of operationtype but the at client browser this error is showing:
XMLHttpRequest cannot load http://localhost:3000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
The primary problem is that you are making a "GET" request. A data payload/HTTP request body cannot be uploaded with an XMLHttpRequest "GET" request. See the specification of XMLHttpRequest: "If stored method is GET act as if the data argument is null."
In order to send data, you should make a "POST" request, in this case:
xmlhttp.open("POST", AjaxURL, true);
In response to updated question:
For security reasons, your AJAX request will not be allowed to access your server hosted at localhost:3000 unless the AJAX request is initiated from a page served by localhost:3000 OR you tell your server to allow "cross-origin" requests. The latter can be accomplished by adding a line like this to your server:
response.setHeader("Access-Control-Allow-Origin", "*");
This sets a header that tells the browser to allow AJAX requests to localhost:3000 even if the request is initiated from a page that was not served by localhost:3000.
Please do the following:
In client.js, output the value Idata(using console.log) right before sending it.
Use the 'Network' tab in Chrome(or equivalent in your favorite browser) to check what is actually being sent.
In server.js, output the value data(using console.log) right after recieving it.
That will probably give you a clue as to where it went wrong, which will help you determine your next course of action. If you still don't know how to proceed, update the question and I will update my answer.
What I can say right now based on my (very lacking) knowledge of node.js, is that if the variable data is being treated as an object, store += data; is not a good idea, as that would mean you are trying to add an object to an (empty) string.
(Probably resulting in the object returning "[object Object]", or some such)
I'm trying to do an AJAX request to https://developers.zomato.com/api/v2.1/search referring to Zomato API
The server has headers:
"access-control-allow-methods": "GET, POST, DELETE, PUT, PATCH, OPTIONS",
"access-control-allow-origin": "*"
The problem is that the API requires additional headers set for user-key. But whenever I set custom headers then chrome would do a pre-flight request by sending an OPTIONS request to the above URL which is failing, and thus the AJAX request is failing as well.
If I don't set the headers, then I don't get a CORS error, but rather a forbidden error from server since I'm not setting user-key header.
Any way to go about this catch-22 situation?
Both Jquery and JavaScript way are failing:
$(document).ready(function () {
$.ajax({
url: 'https://developers.zomato.com/api/v2.1/search',
headers: {
'Accept': 'application/json',
'user_key': 'XXXXX'
},
success: function (data) {
console.log(data);
}
});
});
var xhr = new XMLHttpRequest();
var url = 'https://developers.zomato.com/api/v2.1/search';
xhr.open('GET', url, false);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('user_key', 'XXXXXX');
xhr.send(null);
if (xhr.status == 200) {
console.log(xhr.responseText);
}
Error I'm getting:
OPTIONS https://developers.zomato.com/api/v2.1/search
XMLHttpRequest cannot load https://developers.zomato.com/api/v2.1/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://localhost:8000' is therefore not allowed access. The response had HTTP status code 501.
If somebody wants to reproduce you can get a free user-key here:
https://developers.zomato.com/api
There does not appear to be a work-around for this issue from a browser. The CORS specification requires a browser to preflight the request with the OPTIONS request if any custom headers are required. And, when it does the OPTIONS preflight, it does not include your custom headers because part of what the OPTIONS request is for is to find out what custom headers are allowed to be sent on the request. So, the server is not supposed to require custom headers on the OPTIONS request if it wants this to work from a browser.
So, if the server is requiring the custom headers to be on the OPTIONS request, then the server is just expecting something that will not happen from a browser.
See related answers that describe more about this here:
jQuery CORS Content-type OPTIONS
Cross Domain AJAX preflighting failing Origin check
How do you send a custom header in a cross-domain (CORS) XMLHttpRequest?
Using CORS for Cross-Domain Ajax Requests
And, another user with the same issue here:
Zomato api with angular
It appears the Zomato is not browser friendly, but requires access from a server where you don't have CORS restrictions.
FYI, the error coming back from Zomato is 501 which means NOT IMPLEMENTED for the OPTIONS command. So, it looks like it's not only that the key is not being sent with the OPTIONS command, but that Zomato does not support the OPTIONS command, but that is required for the use of custom headers on a cross-origin request from a browser.
You can't bypass Access-Control-Allow-Headers in preflight response.
However as mentioned by #Jaromanda X in comments, Zomato sends:
Access-Control-Allow-Headers:X-Zomato-API-Key
...meaning you can only send this non-standard header from browser. Also don't go too low-level in request definition when jQuery has pretty and prepared shorthands ...
TL;DR Working example:
$.ajax({
type: "GET", //it's a GET request API
headers: {
'X-Zomato-API-Key': 'YOUR_API_KEY' //only allowed non-standard header
},
url: 'https://developers.zomato.com/api/v2.1/dailymenu', //what do you want
dataType: 'json', //wanted response data type - let jQuery handle the rest...
data: {
//could be directly in URL, but this is more pretty, clear and easier to edit
res_id: 'YOUR_RESTAURANT_OR_PLACE_ID',
},
processData: true, //data is an object => tells jQuery to construct URL params from it
success: function(data) {
console.log(data); //what to do with response data on success
}
});