AngularJs No 'Access-Control-Allow-Origin' - angularjs

I'm trying to make a request with Angular like this:
(function () {
'use strict';
angular.module('app')
.service('requestService',requestService);
function requestService($http) {
this.post = function(url, data) {
return $http({
'method': 'POST',
'url': url,
'data': $.param(
data
)
});
}
}
})();
I receive the error in my console:
XMLHttpRequest cannot load http://lsupport.dev/api/v1/login. 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.
My http://localhost:3000 is build with Gulp. I've already searched a lot on the web, but I cannot find a solution.

You need to enable CORS on the server (remote) to permit the code to execute requests with a different domain.
CORS-Wikipedia

You must need access of the server in which your making the request OR owner of the server need to enable it.
Please check the following post in more details.
Header set Access-Control-Allow-Origin in .htaccess doesn't work
Access-Control-Allow-Origin Multiple Origin Domains?
Homestead is Nginx server Please follow the steps. To solve it.
Handling CORS with Nginx
Access Control Origin nothing to do with AngularJS, It server end issue to respond to the specific request there is different configuration based on your server type like Apache, Nginx.

Related

Access to XMLHttpRequest blocked by CORS Policy in ReactJS using Axios

I'm setting up stripe connect button in my React Component using Axios. I keep getting this error after redirection
Access to XMLHttpRequest at 'https://connect.stripe.com/oauth/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Thankyou.js:40 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
I get the code from the url and create a curl request using axios.Post. This is the code in my redirect URL
// Thankyou.js
export default class Thankyou extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const code = qs.parse(this.props.location.search, {
ignoreQueryPrefix: true
}).code;
const params = {
client_id: "*******************",
client_secret: "**********************",
grant_type: "authorization_code",
code: code
};
axios
.post(
"https://connect.stripe.com/oauth/token",
// apiBaseUrl,
{ params }
)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
console.log(code);
}
render() {
return (
<div>
<h2>Thank you for connecting with us!</h2>
</div>
);
}
}
There is nothing wrong with your code, but most likely the API endpoint the code trying to reach is not setup for JavaScript web app. CORS policy is set on the server-side and enforced primarily on the browser-side.
The best way to work around is to use Stripe's JavaScript solution such as Strip React Elements or Stripe.js.
A hacky way to get around CORS would be setting up Reverse proxy with solutions such as NGINX. For example, you can use the following nginx configuration:
server {
listen 8080;
server_name _;
location / {
proxy_pass http://your-web-app:2020/;
}
location /stripe/ {
proxy_pass https://connect.stripe.com/;
}
}
By doing so, all the API calls to Stripe.com could be through /stripe under your web app's URL. For example, calling http://yourapp/stripe/oauth/token would be same as calling https://connect.stripe.com/oauth/token
That being said, the second solution is hacky and Stripe may decide to block your reverse proxy server.
basically you need to talk to whoever is hosting this https://connect.stripe.com/oauth/token to enable CORS (Cross Origin Resource Sharing )
It is a security measure implemented by most standard browsers to stop unwanted requests to your backend
It's probably because Stripe doesn't provide JavaScript client so you either have to use your own server proxy or use something like "https://cors-anywhere.herokuapp.com/https://connect.stripe.com/oauth/token"
I hope this answer would be useful to new users:
This issue can be easily fixed by using an annotation in your spring boot rest controller class.
Something like below (also ref screenshot):
#CrossOrigin(origins = "http://localhost:4200")
Explicitly mention the react JS server URL that is causing this issue.
Now after adding above annotation (with your react JS server URL) the browser will allow the flow.
All the best.
Learn about CORS
Think about it, there is anything wrong with your axios.post request, it's successfully contacting the server. But there is one more thing to do before the server let you execute or manipulate it's files.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy.
So your cross-origin request and the server Cross-Origin Resource Sharing (CORS) have to match.
How do you solve it?
Depending on your server and the server side programming language your are implementing, you can configure the different parameters to handle your CORS.
For example, you can configure that the only allowed methods will be:
GET HEAD
So if someone try to axios.post to your server with a different method like POST, it will return an error like this:
Access to XMLHttpRequest at 'https://connect.stripe.com/oauth/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Thankyou.js:40 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
Resources:
https://www.w3.org/TR/cors/
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I would suggest reading through this site: https://stripe.com/docs/recipes/elements-react
It gives specific instructions straight from stripe on using their API with react. Good luck!

Cannot connect AngularJs app running on XAMP to API because of CORS error

I've got an AngularJs app running which works with: https://jsonplaceholder.typicode.com/todos
But not with another API (can't show the link) which returns the error:
Access to XMLHttpRequest at 'APIURL' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
21:35:47.396 angular.js:12410 Cross-Origin Read Blocking (CORB) blocked cross-origin response APIURL. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Factory
factory.readProducts = function(){
return $http({
method: 'GET',
url: 'APIURL'
});
console.log('Factory read',factory.readProducts)
};
I've looked at multiple sources and can't come to a conclusion of how to solve this error. I'm running my app locally with XAMPP (or is there an alternative?)
I needed to add Access-Control-Allow-Origin: localhost to my other servers API header

Call Spring-Boot API from AngularJS

I have an API running on Spring Boot and I want to access the data using http call from AngularJS. But it is giving me the error
XMLHttpRequest cannot load http://localhost:9000/transaction-service/transaction/query?id=800103209000150247301466600013. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I know it has something to do with the headers but I don't know how to do it.
You have violated the same origin policy restriction to deal with this in angularjs. You have two solutions
JSON with padding (JSONP) and Cross-origin resource sharing (CORS) headers.
Let’s examine a sample JSONP request and response to see how it works in practice. First of all we need to invoke a JSONP request:
$http
.jsonp('http://angularjs.org/greet.php?callback=JSON_CALLBACK', {
params:{
name:'World'
}
}).success(function (data) {
$scope.greeting = data;
});
Or setting the appropriate CORS headers to allow you to cross domain resource sharing. If you're using Apache :
put the following into your .htaccess file:
Header set Access-Control-Allow-Origin "*"
If you don't have access to configure Apache, you can still send the header from a PHP script. It's a case of adding the following to your PHP scripts:
<?php
header("Access-Control-Allow-Origin: *");

ASP MVC Web api with Angular2 - Http header Access-Control

I have rest application with Angular2 and ASP MVC rest server and I have a problem with communication.
When I send get, I get this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
When I added Access-Control-Allow-Origin to request, I get this error:
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:4200' is therefore not allowed access. The response had HTTP status code 404.
Here is my code:
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' })
this.http.get("http://localhost/App/Users", { withCredentials: true, headers: headers })
.subscribe(response => {
console.log("A");
}, error => {
console.log(error);
});
In web.config is enabled Windows authentication.
Where is problem?
The problem seems here is of CORS. Your angular and WebAPI are using different ports as you're using localhost. (Seems like they are two different projects).
To solve this you can install the nuget package using "Install-Package Microsoft.AspNet.WebApi.Cors" and then in your WebApiConfig file you can simply say "config.EnableCors()". Now the API which you're exposing to the angular part, has to be told that the CORS is supposed to be used there. So you can put the attribute over your controller mentioning the origin, headers and methods. It should work fine after that.
For more reference, you can check this link,
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
On server side when you enabled cors add:
corsAttr.SupportsCredentials = true;
Like this on MVC .net on Application_Start
var corsAttr = new EnableCorsAttribute("http://localhost:4200,http://domain1,http://domain2", "*", "*");
// Enable withCredentials
corsAttr.SupportsCredentials = true;
config.EnableCors(corsAttr);

Access-Control-Allow-Origin error while trying to access url using typescript and angular2

I am trying to retrieve a service which is running on another port.I am getting an error as follows
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.
my service.ts file is as follows
getDeviceInfo(){
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', 'http://localhost:3000',);
headers.append('Access-Control-Allow-Headers','Authorization')
let options = new RequestOptions({
method: RequestMethod.Get,
url: DEVICE_URL,
headers: headers
});
return this.http.request(new Request(options))
.map((res: Response) => res.json());
}
thanks in advance
As per browser policy CORS is not allowed. Howerver if you are using chrome extension POSTMAN or app such as INSOMINA cors error wont occur.
How to pass cors error?
CORS error should only pass by server side.
Consider if your are using express as your server side. Then add following middleware in you app route.
app.use(function(req,res){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Header' , 'authorization');
});
You simply can't. Try Oauth to get information/data from other websites.

Resources