Cannot authenticate into BigCommerce API because of CORS - javascript

I want to make API calls into the BigCommerce API (https://developer.bigcommerce.com/api) using the Basic Authentication.
My AJAX call looks like following:
$.ajax({
type: 'GET',
url: 'https://store-zkk8z5i.mybigcommerce.com/api/v2/products',
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Basic ' + MY_TOKEN,
'Accept': 'application/json'
},
success: function (event) {
debugger
},
error: function (error) {
debugger
}
});
But I keep getting the following error:
XMLHttpRequest cannot load
https://store-zkk8z5i.mybigcommerce.com/api/v2/products. Response to
preflight request doesn't pass access control check: A wildcard '*'
cannot be used in the 'Access-Control-Allow-Origin' header when the
credentials flag is true. Origin
'http://store-zkk8z5i.mybigcommerce.com' is therefore not allowed
access. The credentials mode of an XMLHttpRequest is controlled by the
withCredentials attribute.
I'm pretty sure that my credentials are okay because I get successful responses when I make my requests using cURL.
Any ideas?

I'm pretty sure that my credentials are okay
That's rather beside the point. Look at the error message:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.
Since you are sending credentials, you can't use a wildcard for Access-Control-Allow-Origin.
You have to say Access-Control-Allow-Origin: http://store-zkk8z5i.mybigcommerce.com and not Access-Control-Allow-Origin: *.

Related

How to call web API with GET method basic authentication into jquery() in javascript

Hello I am using this method to read this api it giving CORS error. I have added CORS plugin with chrome then also it is not coming. Please let me know how to solve these to error.
text:
function NoCors() {
debugger;
var uName = "*****";
var passwrd = "*****";
document.write("Enter1");
var url = 'http://219.90.67.163:8207/api/Info/getgismeterdata'
$.ajax({
type: 'GET',
url: url,
crossDomain: true,
//Access-Control-Allow-Credentials: true,
contentType: 'json',
datatype: "application/json",
headers: {
"Authorization": "Basic QXBpVXNlcjpBcGlQYXNz",
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName + ":" + passwrd));
},
success: function (data) {
debugger;
console.log("data")
//Success block
},
error: function (xhr, ajaxOptions, throwError) {
//Error block
},
});
}
error in console:
1. Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
2. Access to XMLHttpRequest at 'http://219.90.67.163:8207/api/Info/getgismeterdata' from origin 'http://localhost:50362' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Before sending the GET request to server, browser automatically send and preflight OPTIONS request, and your server doesn't allow this method. You need to enable OPTIONS method support in your server side (219.90.67.163)
Are you use Bearer Token Authentication?
requst headers try this
headers: {
"Authorization": "Bearer QXBpVXNlcjpBcGlQYXNz",
},
You must setting CORS in Web API
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
The CORS plugin you are using only works for Simple Requests.
Since you are setting an Authorization header you are making a Preflighted Request which your plugin cannot handle.
You need a different approach to handling the Same Origin Policy. Ideally, that would be proper support for CORS on the server you are making the HTTP request to but some other options are listed at the end of this answer.

Can not do cross domain REST API Call from localhost [duplicate]

This question already has an answer here:
Enable CORS in JIRA REST API
(1 answer)
Closed 4 years ago.
I am trying to do login using REST API provided by JIRA in REACT.
But I am getting error like
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:8085' is therefore not allowed access. The response had HTTP status code 403.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Below is my code which I am testing to do sign on.
fetch("https://jira.company.com/rest/auth/latest/session",{
method:'POST',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin" : "*"
},
body:
JSON.stringify({
username:"username",
password : "password"})
}).then(result => console.log(result));
I have also tried with below parameter but it result with same error.
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
I have also looked into documentation for JIRA API but can not find anything for cross domain request access.
Looking for help to do API call across domain.
Try by setting mode: 'cors'
fetch("https://jira.company.com/rest/auth/latest/session", {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
mode: 'cors',
body: JSON.stringify({
username: "username",
password: "password"
})
}).then(function(resp) {
return resp.json();
}).then(function(data) {
console.log(data)
});
Note:In the demo you may see 404 which mean not found because it is not sending username & password

Getting the HTML source of a page in NodeJS

I'm currently struggling to get the HTML source of a webpage in NodeJS due to cors restrictions. Using JQuery I'm making a GET request to a page expecting an HTML response. This however throws the error XMLHttpRequest cannot load https://www.reddit.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. Is there a way to bypass CORS using NodeJS? (like via proxy)
$.ajax({
url: 'https://www.reddit.com/',
headers: {
'Content-Type': 'text/html',
"Access-Control-Allow-Origin": '*'
},
type: "GET",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
I'm also using webpack dev server with the following headers
headers: {
"Access-Control-Allow-Origin": '*',
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
}
Do not use jquery in nodejs, you can use this libs to archieve what you need:
isomorphic-fetch
request
Hope it helps

Isomorphic fetch gives CORS error

I am trying to covert my jQuery ajax call to use isomorphic fetch instead
My jQuery ajax call looks like this:
$.ajax({
url: 'myURL',
dataType: "script",
cache: true,
success() {
notify();
}
});
and my isomorphic fetch looks like this:
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/javascript');
fetch('myURL', {
headers: myHeaders,
mode: 'cors',
cache: 'default'
}).then(function(){
notify();
}).catch(function(error) {
console.log('request failed', error)
})
In the isomorphic-fetch version I am getting a CORS error in the browser:
"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8080' is therefore not allowed access. The response had HTTP status code 501. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
However, the ajax call works fine.
What am I doing wrong?

Ajax call to Mailchimp API 3.0 returns HTTP 501

I am trying to simply subscribe a mail address with the name to a MailChimp list.
I thought this should be very easy but I can't manage to post the mail address there.
You can find the full code here (key=authkey):
$(document).ready(function(){
$('#blogsignup').submit(function(event){
event.preventDefault();
$.ajax({
url : "https://us12.api.mailchimp.com/3.0/lists/247e2f0702/members/",
dataType : "json",
headers: { "Content-Type":"application/json", 'Access-Control-Allow-Origin': '*', "Accept": "application/json", "Authorization": "key-us12" },
type : 'POST',
contentType: "application/json",
data : {
apikey: "key",
email_address: $('#TBemail').val(),
status: 'subscribed',
merge_fields: {
FNAME: "subscriberFirstName",
LNAME: "subscriberLastName"
}
},
// Try to send also before
beforeSend: function(xhr) { xhr.setRequestHeader("Authorization",
"Basic " + btoa("api:" + "key-us12"));
},
success : function (data) {
$('#signup').html("Thanks for signing up. We will contact you as fast as possible.");
},
error : function (data, errorThrown) {
alert(errorThrown);
console.log(data);
}
});
});
});
The function is triggered when clicking the submit button.
I always get the alert "error" and it's saying
XMLHttpRequest cannot load https://us12.api.mailchimp.com/3.0/lists/247e2f0702/members/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://preprod.travelgap.io' is therefore not allowed access.
The response had HTTP status code 501.
I was also trying jsonp as Datatype then I get a 401 error. Authkey not passed.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This means that the client (making the AJAX call) is not permitted to directly hit the API. Your current architecture:
Client (any origin) ---> MailChimp API
What you should do, as suggested already, is use your server to proxy over the request to the remote API, so that you don't violate their CORS rule. You should add an API endpoint on your server which, when accessed by a client, makes a server-side network request to the MailChimp API.
Client (any origin) ---> Server (known, whitelisted origin) ---> MailChimp API
Also, your API key should never exist in client code. Your API key should be considered a secret available only server-side. The latter architecture ensures that this is the case.

Categories

Resources