Call Spring-Boot API from AngularJS - 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: *");

Related

How to How to fix "No 'Access-Control-Allow-Origin' header is present on the requested resource" in post call in reactJS using Fetch method

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 .

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

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);

Mixed Content: The page at 'URL' was loaded over HTTPS | AngularJS

Im making an app, where I want to sent $http.get requests to duckduckgo's API but their requests are done over HTTP. Seeing my site is HTTP is get the following error:
angular.js:11756 Mixed Content:
The page at 'URL' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint 'http://api.duckduckgo.com/'.
This request has been blocked; the content must be served over HTTPS.
When I adding the s to my request, I obviously get the following (seeing the CORS isn't setup):
XMLHttpRequest cannot load:
https://api.duckduckgo.com/?q=Undulated%20Tinamou&format=json&pretty=1.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://URL' is therefore not allowed access. The response had HTTP status code 405.
My question: Is there any was for me to get the json and bypass one of the two stated above?
Edit1:
$http.get('https://api.duckduckgo.com/?q=' + birdname + '&format=json&callback=jsonp&pretty=1').then(function(res){
console.log(res.data);
});
I also tried the following:
$http.jsonp('https://api.duckduckgo.com/?q=' + birdname + '&format=json&callback=jsonp&pretty=1').then(function(res){
console.log(res.data);
});
With the second, I am getting the following error:
Uncaught ReferenceError: json is not defined

AngularJs No 'Access-Control-Allow-Origin'

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.

Resources