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);
Related
Getting below error while i call DotNet core API method from ReactJS post call using Fetch options.
ReactJS post call only i am getting this error, below way i was tried.
Jquery get/post request - working fine
Postman get/post request - working fine
Swagger get/post request - working fine
ReactJS get request - working fine
ReactJS post request - Not working fine
"Access to fetch at 'https://localhost:44352/api/Address/CheckAvailability' from origin 'http://localhost:3000' has been 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
/*ReactJS Code: */
export function saveAddress(address) {
return fetch(baseURL + "Address/CheckAvailability", {
method: "POST",
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(address),
}).then(handleResponse)
.catch(handleError);
}
/*Dot.Net core Code: */
[HttpPost]
public ActionResult CheckAvailability([FromBody]ReqAddressDetailsDto request)
{
if ((request) == null)
{
return NotFound();
}
return Ok(request);
}
If your client application (the React web app) is on another scheme (any of http/https, domain or port is different), you need to have CORS enabled on your ASP.NET Core back-end.
In the Startup.cs file, you need to add this:
In ConfigureServices()
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins("http://localhost:3000/")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
In Configure() put this just before app.UseMvc():
app.UseCors();
Check this link for more info:
https://learn.microsoft.com/en-us/aspnet/core/security/cors
did you enabled / configured cors in this .net core api?
How to enable CORS in ASP.NET Core
You can check CORS headers on your backend script.
The CORS standard manages cross-origin requests by adding new HTTP headers to the standard list of headers. The following are the new HTTP headers added by the CORS standard:
Access-Control-Allow-Origin
Access-Control-Allow-Credentials
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Request-Headers
Access-Control-Request-Method
Origin
These headers are all important, but let’s we focus on the following header:
Access-Control-Allow-Origin
You should define Access-Control-Allow-Origin header as '*'. I guess, it may be solved your problem simply. A little example for PHP:
<?php
header("Access-Control-Allow-Origin: *");
You may find an info of each CORS header the following: CORS Headers.
If you want to learn more details about CORS, You can follow this link.
This status code is a useful hint to understand that the server doesn’t support OPTIONS requests.
Add the corresponding header on the server side when handling the OPTIONS method. We will then have the following requests:
Access-Control-Allow-Headers : Content-type
Hopefully this solves .
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: *");
I am trying to debug my angular app with chrome dev console.I want to send a get request to a local server from angular. I've tried the following:
$http = angular.element($0).injector().get('$http');
$base64 = angular.element($0).injector().get('$base64');
var auth = $base64.encode("user:passwd");
var authHeaders = {"Authorization": "Basic " + auth,"Access-Control-Allow-Origin":"*"};
$http.get("url",{headers:authHeaders,method:"GET"})
After reading this answer:
https://stackoverflow.com/a/30296149/1496826
I thought that custom header is the problem. So, I tried putting the authorization headers in the body:
$http.get("url",{data: {"Authorization": "Basic " + auth,"Access-Control-Allow-Origin":"*"},method:"GET"})
But I am still getting the same error:
XMLHttpRequest cannot load "url". No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'null' is
therefore not allowed access. The response had HTTP status code 401.
This same get request works fine from Postman:
var settings = {
"async": true,
"crossDomain": true,
"url": "url",
"method": "GET",
"headers": {
"authorization": "Basic bWdhcasdasd",
"cache-control": "no-cache",
"postman-token": "XXXXXX-XXXXXX-xXXXX-xXXXX"
}
}
I have tried several other variation like - $http default / common header etc. but everything failed. Please help.
this is a CORS issue.
CORS headers must be handled server side, i don't see your server side code here but in order to let this error disappear you must specify which domain are allowed to request resources.
the exception is caused by the browser that intercept the server response check the headers and if it doesn't find the Allow-Control-Allow-Origin header it won't forward the response to your code (this happens only for cross origin request).
This is why Postman let you see the response, because it doesn't do what chrome does, doesn't make any check.
As i said the correct solution is to fix your server side code and specify the Allow-Control-Allow-Origin header , alternatively a quick but temporary workaround is to install this plugin for chrome that will intercept the server response and add the Allow-Control-Allow-Origin to * (means any domain) this trick will fool chrome and make you see the response.
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.
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.