I try to get issues from redmine via them Rest Api. When I call it from Postman I get response, but when I do it from my angular App I get such error
OPTIONS https://redmine.ourDomain.net/issues.json 404 (Not Found)
XMLHttpRequest cannot load https://redmine.ourDomain.net/issues.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:3000' is therefore not allowed access. The response had HTTP status code 404.
Its how I do it in Angular
login(user: User): Observable<boolean> {
var headers: Headers = new Headers();
headers.append("Authorization", "Basic " + btoa(user.login + ":" + user.password));
let options = new RequestOptions({ headers: headers });
return this.http.get("https://redmine.ourDomain.net/issues.json", options)
.map((response: Response) => {
debugger;
if (response.status == 200) {
// set token property
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ user }));
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
});
}
And there how request looks in my browser
You'll need to enable CORS access on the backend: http://www.redmine.org/plugins/redmine_cors
Here's a nice extension that will let you test frontend code outside of normal CORS restrictions. It's strictly for testing and won't help a production app, but nice to have: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
CORS must be set up in the backend. Please note that is NOT a good practice to allow all origins Access-Control-Allow-Origin: '*' and that you will need to specify the other headers as well:
Access-Control-Allow-Methods: GET, OPTIONS
Access-Control-Allow-Headers: authorization.
Related
I am attempting to follow this EBAY User Consent API article https://developer.ebay.com/api-docs/static/oauth-consent-request.html
but I am getting a CORS error "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."
I've read numerous Cors posts here this one being a good one: XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header but none of these solutions seem to work.
a pointer in the right direction would be great.
$(document).on('click','.ebay_access', async function(event) {
let scopes = encodeURIComponent("https://api.ebay.com/oauth/api_scope https://api.ebay.com/oauth/api_scope/sell.marketing.readonly https://api.ebay.com/oauth/api_scope/sell.marketing https://api.ebay.com/oauth/api_scope/sell.inventory.readonly https://api.ebay.com/oauth/api_scope/sell.inventory https://api.ebay.com/oauth/api_scope/sell.account.readonly https://api.ebay.com/oauth/api_scope/sell.account https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly https://api.ebay.com/oauth/api_scope/sell.fulfillment https://api.ebay.com/oauth/api_scope/sell.analytics.readonly https://api.ebay.com/oauth/api_scope/sell.finances https://api.ebay.com/oauth/api_scope/sell.payment.dispute https://api.ebay.com/oauth/api_scope/commerce.identity.readonly https://api.ebay.com/oauth/api_scope/commerce.notification.subscription https://api.ebay.com/oauth/api_scope/commerce.notification.subscription.readonly");
let clientId = "{{env('EBAY_APIKEY')}}";
let clientSecret = "{{env('EBAY_API_CERT_NAME')}}";
let oAuthCredentials64 = btoa(clientId + ":" + clientSecret);
let endpoint = 'https://api.ebay.com/identity/v1/oauth2/token';
try{
let response = await fetch(endpoint,
{
method: "POST",
headers:
{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${oAuthCredentials64}`
},
body:
"grant_type=client_credentials&scope=" + scopes
}
);
let responseJson = await response.json();
console.log("CLIENT ACCESS TOKEN", responseJson);
} catch(err){
console.log("error: ", err);
};
}); //end function
The request you are making seems to be an authentication request, or "consent request", as eBay call it. This must be made to the authorization endpoint (probably https://api.ebay.com/identity/v1/oauth2/authorize). But you make it to the token endpoint (https://api.ebay.com/identity/v1/oauth2/token), as if it were a token request. But the token request is only the second step ("Exchanging the authorization code for a User access token").
Moreover, neither the authentication request nor the token request are CORS requests:
The authentication request must happen in a visible browsing context, as explained here. The user can only consent if they see what is going on.
The token request is not made by the browser, because this would expose the secret (as pointed out in Jags's answer). It must be made by your server.
In other words: No CORS should be involved at all. The eBay API article explains this correctly.
There are multiple issues here.
In general, if the URL - domain on your browser is not same as the ajax call browser is making then you get this error.
Seems that you have copied the code which was meant for server side execution. You should NEVER expose your credentials to client side. Anyone can use your steal your credentials.
The github link you provided as reference is for server side nodejs application which is running as an app and not under browser.
So I've been experiencing this CORS error and a 401 and have tried chrome plugins to allow for cors with no luck. Here are the errors I'm getting after disabling cors via the plugin:
Access to fetch at 'https://api.playground.klarna.com/payments/v1/sessions' from origin 'https://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Failed to load resource: net::ERR_FAILED
Error: TypeError: Failed to fetch
Before enabling the CORS Chrome Extension I was receiving a Allow-Access-Control-Origin is not set on the first error message. Along with this in the network tab I'm getting a 401 Preflight which indicates unauthorized but I'm setting the Authorization header with the correct credentials so not sure what's happening here. I'm using the codeigniter php framework.
I'm using Basic auth with:
var auth = 'Basic ' + btoa(username:password);
Here's the code:
let postDataSession = {
"purchase_country" : bookingData.purchase_country,
"purchase_currency" : bookingData.purchase_currency,
"locale" : bookingData.locale,
"order_amount" : bookingData.order_amount,
"order_tax_amount" : 0,
"order_lines" : [{
//"type" : "physical",
"reference" : bookingData.order_lines.reference,
"name" : bookingData.item_name,
"quantity" : 1,
"unit_price" : bookingData.order_amount,
"tax_rate" : 0,
"total_amount" : bookingData.order_amount,
"total_discount_amount": 0,
"total_tax_amount" : 0
}]
};
fetch('https://api.playground.klarna.com/payments/v1/sessions', {
method: 'POST',
//mode: 'no-cors',
//Authorization: auth,
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
//'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Headers' : 'pm-u, pm-h0, pm-h1, pm-h3, pm-o0, pm-o1, pm-o2, pm-o3, authorization',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Origin': 'https://localhost',
'ACCESS-CONTROL-MAX-AGE' : 3600,
'referrer-policy': 'no-referrer-when-downgrade'
},
body: JSON.stringify(postDataSession),
})
.then(function(response) {
//The following method initializes the Klarna Payments JS library
//window.location.href = baseurl + "customer/klarna_checkout_page";
if (!response.ok) {
return response.text().then(result => Promise.reject(new Error(result)));
console.log(response.status);
}
console.log(response.json(), response);
return response.json();
})
// .then(function(session) {
// window.location.href = baseurl + "customer/klarna_checkout_page";
// })
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
console.log(result);
})
.catch(function(error) {
console.error('Error:', error);
});
I've tried it the mode set to no-cors and receive the same response. I've used postman to post the request with the same data and in postman a response is received. Not sure if I'm either missing or overlooking something so a fresh perspective would be helpful. Does anyone have any idea how to proceed with resolving this issue? I want to avoid having to deploy this code to the live domain and be able to test the response on localhost, not sure if that's at all possible with cors.
Browser extensions are notoriously useless at dealing with preflighted requests. It won't help here.
No-cors mode makes the browser silently fail anything that requires CORS permission instead of throwing an exception. It won't help here.
Postman isn't a browser. It's requests aren't triggered by visiting a website. It doesn't implement the Same Origin Policy and doesn't need permission from CORS.
I'm getting a 401 Preflight which indicates unauthorized but I'm setting the Authorization header with the correct credentials so not sure what's happening here.
The browser is making a preflight request asking permission to send a POST request with credentials.
The server is getting the preflight request and complaining that it doesn't have credentials on it.
Either:
Change the server you are making the request to so it grants you permission in your development environment. It needs to allow OPTIONS requests without credentials on them.
Use a proxy that relays your requests to the server
Is your backend .net core web services? If so, I have seen this problem when you call UseCors after UseAuthentication in your pipeline. If you do that, you will need an authenticated token to do the preflight which is why you get a cors error throwing the exception. Move UseCors to before UseAuthentication so that a CORS response does not have to go through the Authentication middleware first.
I have pretty basic axios code:
axios.get(GEO_IP)
.then(res => res)
.catch(err => err);
Also, I set next axios defaults:
axios.defaults.headers["content-type"] = "application/json";
axios.defaults.headers.common.authorization = `Bearer ${token}`;
authorization token no needed for this public API. When I try to fire query using axios.get, I see next error in console:
Failed to load https://ipfind.co/me?auth=8964b0f3-4da1-46eb-bcb4-07a9614a6946: 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:3000' is therefore not allowed access.
When I rewrite axios using native XMLHttpRequest:
new Promise((resolve, reject) => {
const http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
// result
}
};
http.open("GET", GEO_IP, true);
http.send();
});`
Everything works fine, without any errors. Could someone clarify why axios query causes the error and how I can fix it?
The error message says:
Response to preflight request
This has nothing to do with axios. You are trying to send different requests. When you are using axios, you are setting up the request in such a way that a preflight is required.
axios.defaults.headers["content-type"] = "application/json";
axios.defaults.headers.common.authorization = `Bearer ${token}`;
Either of the above would trigger a preflight.
The XMLHttpRequest version (which doesn't set HTTP headers) doesn't require a preflight, so the server not supporting the preflight isn't a problem.
This means that while your server sends the right CORS headers for the GET request, it isn't for the OPTIONS request that is being sent by axios as part of the preflight request.
Some requests don't require a preflight request. But I'm guessing that axios always sends one.
See MDN for more details on this.
I have application where I getting code from stash raw file. Scrapping from public repositories is simple, it looks like this:
public getRawFile(rawLink: string) {
return this.http.get(rawLink).map((res: Response) => res.text());
}
But now I would like to get code from stash raw file, but from private repository. If user have access(is logged into stash) than source code from raw file is loaded.
If I trying same way, I getting respone:
XMLHttpRequest cannot load 'private_stash_file_link'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
EXCEPTION: Response with status: 0 for URL: null
Uncaught Response with status: 0 for URL: null
How can I handle this, cookies, specific options for get request, is it even possible?
EDIT 1.
Tried:
public getRawFile(link: string) {
let headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET, OPTIONS');
headers.append('Access-Control-Allow-Origin', '*');
let options = new RequestOptions({headers: headers, withCredentials: true});
return this.http.get(link, options).map((res: Response) => res.text());
}
but same result for private repository..
plunker
The server that you are making the request to has to implement CORS to grant JavaScript from your website access (Cross Origin Resource Sharing (CORS)). So if you have access to the place where you are scraping, then add the following HTTP headers at the response of the receiving end:
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *.example.com
Make sure to replace "*.example.com" with the domain name of the host that is sending the data/getting the data. Doing this should fix your problem.
I have two app with nodejs and angularjs.nodejs app has some code like this :
require('http').createServer(function(req, res) {
req.setEncoding('utf8');
var body = '';
var result = '';
req.on('data', function(data) {
// console.log("ONDATA");
//var _data = parseInput( data,req.url.toString());
var _data = parseInputForClient(data, req.url.toString());
switch (req.url.toString()) {
case "/cubes":
{
and this app host on http://localhost:4000.angularjs app host with node http-server module on localhost://www.localhost:3030.in one of my angularjs service i have some thing like this :
fetch:function(){
var data = '{somedata:"somedata"}';
return $http.post('http://localhost:4000/cubes',data).success(function(cubes){
console.log(cubes);
});
}
but when this service send a request to server get this error:
XMLHttpRequest cannot load http://localhost:4000/cubes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3030' is therefore not allowed access.
so i search the web and stackoverflow to find some topic and i find this and this . according to these topics i change the header of response in the server to something like this :
res.writeHead(200, {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*"
});
res.end(JSON.stringify(result));
but this dose'nt work.I try with firefox,chrome and also check the request with Telerik Fiddler Web Debugger but the server still pending and i get the Access Control Allow Origin error.
You do POST request, which generates preflight request according to CORS specification: http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ and https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Your server should also respond to OPTIONS method (besides POST), and return Access-Control-Allow-Origin there too.
You can see it's the cause, because when your code creates request in Network tab (or in Fiddler proxy debugger) you should see OPTIONS request with ORIGIN header