Can not retrieve data between domain and sub domain - javascript

I have an Ajax request on a domian xyz.com and I am performing an
Ajax request from xyz.com to pull data from abc.xyz.com
var request = $.ajax({
type: "POST",
url: "https://abc.mno.com/vending/mainvending.php",
data: {vlu:"1"},
dataType: 'json',
timeout: 10000,
crossDomain: true,
async: true,
cache: false,
headers: { "cache-control": "no-cache" },
error: function( jqXHR, textStatus, errorThrown )
{
alert("error : " + errorThrown + " text :"+textStatus + " j :" +jqXHR.status);
// alert(jqXHR.responseText);
},
success: Succeeded,
beforeSend: function( xhr ) { }
});
but I keep getting this error which is consoled out in the browser (Chrome)
XMLHttpRequest cannot load https://abc.xyz.com/vending/mainvending.php. Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight response.
In the mainvending.php the codes are as follows
<?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 'vendors.php';
if(!empty($_POST)){
/** Other codes follow **/
}else{
/** Other codes follow **/
}
?>
what am I not doing or what am I doing wrong? The domain name is xyz and the domain I am retrieving data from is of a sub domain could that be the issue and how do I go around this.

Your error message says that the server isn't allowing you to send a cache-control header.
You are doing that here:
headers: { "cache-control": "no-cache" },
… cache-control is a response header, so it makes no sense to include it in a request.
Remove that line.
(Alternatively, you could add it to the Access-Control-Allow-Headers header that you are already setting).

You can do one of the following two things:-
Remove this key-value pair from your AJAX config
headers: { "cache-control": "no-cache" },
Add cache-control header to your PHP code to allow it.
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, cache-control');

Try setting these headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Related

ajax google forms blocked by CORS

I try to send data to google forms, by using google form input names with ajax.
But getting cors error.
My ajax:
$.ajax({
url: 'https://docs.google.com/forms/u/0/d/e/FORM-ID/formResponse',
type: 'POST',
crossDomain: true,
dataType: "xml",
data: data,
statusCode: {
0: function() {
console.log('Enter on error');
swal({
title: "Error!",
text: "error",
type: "error",
confirmButtonText: "Ok"
});
},
200: function() {
console.log('Enter on success');
swal({
title: "Success",
text: "Your information submitted successfully!",
type: "success",
confirmButtonText: "Ok"
});
}
}
});
My Headers:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");
?>
Errors:
Access to XMLHttpRequest at
'https://docs.google.com/forms/u/0/d/e/FORM-ID/formResponse' from
origin 'http://localhost' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
jquery-3.2.1.min.js:4 POST
https://docs.google.com/forms/u/0/d/e/FORM-ID/formResponse
net::ERR_FAILED

Trying to get json from mercadolibre api but always gets the same cors error?

I am trying to consume a mercadolibre API that returns a json with some data that I need to use.
But everytime I tried by an ajax GET request it returns the same error:
"Response to preflight request doesn't pass access control check: It does not have HTTP ok status"
I Think it is a CORS issue, but I have tried everything on headers while the request (which is corssed domain) and nothing seems to work.
Here is the way I am doing the ajax request:
if (obtieneCotizaciones == 'true' && token != null) {
var sellerID = '499777238';
$.ajax({
type: "GET",
url: "https://api.mercadolibre.com/quotations?access_token="+token+"&seller.id="+sellerID+"&caller.type=seller",
contentType: "application/json",
headers: {
'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods':'GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS',
'Access-Control-Max-Age': '604800',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Headers':'application/json',
'Access-Control-Allow-Headers': 'x-requested-with'
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error)
console.log("FAIL");
}
});
}
Any Idea how could I solve this? don't mind for 'token' and 'obtieneCotizaciones' variables, they are just needed to make the request and I obtein them before doing the request.
Have you tried removing all of the headers? They are triggering a pre-flight which is why it's failing with that error.

how to post data to web service

Problem Description:- i am trying to call web services of different domain(i.e. Systems are not connected locally with each other) so i am getting error:-"Failed to load https://sap.atlassian.net/: Response for preflight is invalid (redirect)"
var username = "pra#sap.com";
var password = "Sa8";
$.ajax({
type: 'POST',
data: data1,
url: 'https://sap.atlassian.net',
dataType: 'json',
contentType: "application/json",
crossDomain: true,
ProcessData: true,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "POST, GET, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "accept, X-Custom-Header, x-requested-with, X-Auth-Token, Content-Type"
},
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Atlassian-Token", "no-check");
xhr.setRequestHeader('Authorization', "Basic" + btoa(username + ":" + password));
},
success: function(data) {
console.log("success");
},
error: function(e) {
console.log(e);
}
});
First, you might need to double-check URL. There must be some relative URL as well.
This is related to preflight. See https://www.gyanblog.com/gyan/39-explaining-issue-response-preflight-request-doesnt-pass-access-control-check
Can you post detailed stacktrace?
PS: Its always bad practice of putting your username/password openly. You should immediately change your password!

How to get headers element in node js

I would like to get headers element in server side with node js I try these two codes in client side:
CODE 1
var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ayI6IjU5Mjg0YjQ0MzNhNjU2MmRlNDI1ZGU5MCIsImlhdCI6MTQ5NjY5NjA1NiwiZXhwIjoyOTkzMzk1NzEyfQ.BQskPVT-h-Io4p3Hqraq2qRmVlp_pWAEw5rnIIEA4vk';
$.ajax({
url: 'YourRestEndPoint',
headers: {
'Authorization':'Basic' + token
},
method: 'POST',
dataType: 'json',
data: YourData,
success: function(data){
console.log('succes: '+data);
}
});
Code 2:
$.ajax({
url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
data: { signature: authHeader },
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader(
'Authorization':'Basic' + token);
},
success: function() { alert('Success!' + authHeader); }
});
And here the code server:
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Authorization");
console.log(req.headers['authorization']);
I can't get the token in the server side.
In Code 1, you have 'Authorization' as the property name in your header. However, in your code, you console.log 'authorization'.
Try the same capitalization of both. Let me know if the capital was an error with copying and pasting.

Access-Control-Allow-Headers returning two values

I am having trouble submitting to an API when using IE 11. I believe the problem is the API is returning TWO Access-Control-Allow-Headers in IE 11. In Chrome and Firefox, it only returns one. Also, the Access-Control-Allow-Origin returns a URL in IE 11, but returns a * in Chrome and FF. Any help in resolving this issue would be greatly appreciated as I have spend double digit hours trying to resolve with no success. The logic of what happens after submit is based on the response, but it is kicking out with errors on IE so that logic never gets executed ( SEC7123: Request header content-type was not present in the Access-Control-Allow-Headers list. - SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied. ).
IE 11 Response Headers:
Access-Control-Allow-Headers bearer_token
Access-Control-Allow-Headers authorization, x-date, Content-Type, if-none-match
Access-Control-Allow-Origin - https://this.that.com
Chrome and FF Response Headers (the ones that are different from IE):
Access-Control-Allow-Headers - authorization, x-date, etag, content-type, range, if-none-match
Access-Control-Allow-Origin - *
Code being used to submit:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$("#ajaxform").submit(function(e)
{
$.ajax({
url: 'https://this.that.com?firstname=test&lastname=test&email=test55#n2.com',
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: '{}',
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXXXXXX'
},
success: function( data, status, jQxhr ){
var thisResponse = jQxhr.responseText;
var trimResp = thisResponse.slice(2, -2);
thisParse = jQuery.parseJSON(trimResp);
var thisStatus = thisParse.status;
console.log(jQxhr);
//alert(thisStatus);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log("readyState: " + jqXhr.readyState);
console.log("responseText: "+ jqXhr.responseText);
console.log("status: " + jqXhr.status);
console.log("text status: " + textStatus);
console.log(jqXhr.getAllResponseHeaders);
}
});
e.preventDefault();
});
Thanks for taking the time to read through this.
Cheers~
C

Categories