CORS policy 'Access-Control-Allow-Origin' (Anguar 8 and Servlet) - java

Getting error while making post request from Angular app to servlet doPost method.
Angular application make 2 request 1 for doGet method and other doPost method.
In doGet method i added following heders as follows
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "GET");
resp.setHeader("Access-Control-Max-Age", "3600");
resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
and solved my CORS problem for GET call.
but doPost method give CORS error even i added same header in doPost method.
angular console shows
Access to XMLHttpRequest at 'http://localhost:8080/server/config' from origin 'http://localhost:4200' 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.
Server is written in servlet and running on port 8080.
Front end is written in Angular 8 and running on port 4200.
How to solve CORS error for post call...
Thanks..

In your code, only allow GET method. Update your code like:
resp.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");

Related

Can not send POST with body

I have issue in my application. I have various REST enpoints which are working fine. But now I want to send POST request with body. I already have 2 endpoints for POST method, but data are send using PathParam.
I created new endpoint, but when I send request I am getting CORS error. When I use the same endpoint without body in request everything is okay but of course at backend side I do not get any data from frontend (I have breakpoint inside method).
this is how I send request from my angular application:
post(requestUrl: string, body?: any): Observable<any> {
return this.httpClient.post<any>(this.API_URL + requestUrl, {password: 'test'});
}
After sending request I got:
Access to XMLHttpRequest at 'http://localhost:8080/...' from origin 'http://localhost:4200' 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 I send request like this (without body) this endpoint works fine:
post(requestUrl: string, body?: any): Observable<any> {
return this.httpClient.post<any>(this.API_URL + requestUrl);
}
At backend side I have added settings for CORS:
return Response.ok(object).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.allow("OPTIONS").build();
When I am sending request from Insomnia everything is ok - I can send body and I am getting sent data on backend.
Should I somehow set request headers at frontend side?
Here is my AdminApiController class:
#Path("/admin")
#RequestScoped
public class AdminApiController extends BaseApiController {
#Inject
private AdminAssembler adminAssembler;
#POST
#Path("/login")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response login(LoginRequest request) {
return Response.ok(adminAssembler.login(request))
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Headers", "Content-Type")
.allow("OPTIONS").build();
}
}
When your angular application sends a JSON payload in a POST request, it probably adds the header Content-Type: application/json. This header classifies the POST request as a "non-simple" request (that is, a request that cannot result out of an HTML <form> element without additional Javascript). Such "non-simple" requests cause to browser to make a preceding preflight request, that is an OPTIONS request with headers
Origin: http://localhost:4200
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
to which the server must respond with an Access-Control-Allow-Origin header and Access-Control-Allow-Headers: Content-Type. If it does not, the browser will not make the POST request and show an error like you observed.
Your Java code covers only #POST, not #OPTIONS, that's why the server does not respond to the preflight request with the necessary headers. How best to handle the OPTIONS requests for all endpoints on your server is a question for Java experts (which I am not).
You need to define your httpOptions.
Try this.
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
post(requestUrl: string, body?: any): Observable<any> {
this.httpClient.post<any>(this.API_URL + requestUrl, {password: 'test'}, this.httpOptions)
}
Let me know if it worked for you.

No 'Access-Control-Allow-Origin' is present on requested resource

I am having a weird issue where my client side request is telling me I have no 'Access-Control-Allow-Origin' present when making an HTTP POST request to a java servlet I have hosted and live. I have made sure to add the necessary headers in my response to clear up CORS requests issues but it does not seem to be recognizing the headers.
Here is my angular $http.post request I am making from the client side:
var parameter = JSON.stringify(details);
var req = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: parameter
}
$http.post(localurl, req).
then(function(response) {
});
Here is the error I am getting from chrome:
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:8081' is therefore not allowed access.
Here is the beginning of my java servlet doPost function:
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res) {
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
res.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
I have been searching various stackoverflow questions and those response headers I am setting in my servlet should clear up the CORS requests issues but it does not seem to be recognizing the response headers I am setting at the beginning of the doPost function. Any and all help is very appreciated. Thanks in advance.
The problem is on your back-end, if yours is nodejs, should be like this way to allow Access-Control-Allow-Origin:
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});

How to enable cors issue in Angular2 with Backend as Liferay server

I am new to Angular2. I have to create new Angular application and Need to use services from Liferay server.
But When I call the Service using below code, it is giving Cors error.
var headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Content-Type", "application/x-www-form-urlencoded");
let params: URLSearchParams = new URLSearchParams();
this.http.get(localStorage.getItem('domainName')+'/service-name', {headers: headers})
.subscribe(response => {
// login successful if there's a jwt token in the response
console.log('Response'+response.json());
});
My backend method is GET and I have added Cors filter property in my /webapps/Root/web.xml file
BUt in browser console it is giving below error:
XMLHttpRequest cannot load http://localhost:9080/service-name. 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 401.
This error comes up when the backend's response does not have the necessary Access-Control-Allow-Origin header. Please double check that the backend's headers are properly configured. Also, the frontend's request does not have to have the Access-Control-Allow-Origin header ever.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'xxx' is therefore not allowed access

I tried to integrate paypal payment gateway into my application.
Simply I am calling java webservice using angularjs get method.
Below the angularjs http get method code
$http({
method : 'GET',
url : 'http://localhost:8080/xxxx/redirect'
}).then(function successCallback(response) {
console.info("success");
});
The Java side code tried is-
#RequestMapping(value = "/redirect", method = RequestMethod.GET, headers = "Accept=application/json")
public ModelAndView method(Payment pPayment) {
String amount=pPayment.getAmount();
String url="https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=wipro-seller#gmail.com&first_name=smartCity&city=Madurai&state=Tamilnadu&item_name=shirt&amount=10&night_phone_a=9513335437&item_name=shirt&address1=wipro-seller#gmail.com&business=k.tapankumar#gmail.com&quantity=1&currency=USD";
return new ModelAndView("redirect:" + url);
}
I am calling Paypal test account url from Java server side only, but still I am getting below error
XMLHttpRequest cannot load https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=wipro-se…o-seller#gmail.com&business=k.tapankumar#gmail.com&quantity=1&currency=USD. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Kindly Let me know where I did wrong..
You will need to enable cross origin requests (CORS) for your HTTP requests.
Spring Documentation documents on how to enable this really well. Find it here. I suggest you read through it and try it out. If it still doesn't work, post here.
More on CORS here.
You should allow cross origin request from client side as well.
try to run after installing a chrome plugin for cross origin
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
this is the link for the one which i use.
Also you should change your headers to allow cors like this
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

Access Control Allow Origin Error in jersey web service

I need to enable CORS (Cross Origin Resourcing) on my App, I am using jersey in Webservice. Setting the Access control origin in response header isn't helping.
headers.put("Access-Control-Allow-Origin", "*");
headers.put("Access-Control-Allow-Methods","GET, POST, DELETE, PUT, OPTIONS, HEAD");
headers.put("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
headers.put("Access-Control-Max-Age", "1728000");
headers.put("Access-Control-Allow-Credentials", "true");
Apart from trying to set the header I even tried ContainerResponseFilter which didn't work, setting this on the client side using angular in myApp.config as below,
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
also didn't work.
jersey version : 1.19
java: 1.7

Categories