Play framework AngularJs CORS post json - json

I have a frontend in AngularJs and a playframework 2 Scala backend. Looking at this to add CORs to the backend - I have two endpoints a GET and POST
GET /api/question/:id controllers.Questions.getQuestion(id: String)
POST /api/question/:id controllers.Questions.postQuestion(id: String)
This solution provided in the other response works for the GET but not for the POST
def getQuestion(key:String) = CorsAction{
....
}
def postQuestion(key:String) = CorsAction(parse.json){
req =>
........
}
What I understood is that the CORsAction (which extends ActionBuilder) can also accept methods which a bodyparser and thus should essentially work for POST requests as well.
This is what I see in the browser console when i hit POST from my front end.
OPTIONS http://localhost:9000/api/question/abc123 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3001' is therefore not allowed access. angular.js:7997
XMLHttpRequest cannot load http://localhost:9000/api/question/abc123. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3001' is therefore not allowed access.

So I'm not sure the exact problem but adding the following to the routes
fixed the problem
OPTIONS /api/question/:id controllers.Application.preflight(id)
Where the preflight endpont just returns Ok with the CORs headers. But I would have thought that the CorsAction was supposed to take care of this. Anyways, moving on.

Related

Fetching data to phonope api

I have fetched data to phonepe api "https://api-preprod.phonepe.com/apis/merchant-simulator/pg/v1/pay" the base 64 payload as request in body and Sha256 x-verify as x-verify in headers. When i fetch data on phonepe website postman it works and i get a transaction initiated response but It doesn't work on either localhost or on official website "wearmiho.com".
Shows error
""Access to fetch at 'https://api-preprod.phonepe.com/apis/merchant-simulator/pg/v1/pay' from origin 'https://www.wearmiho.com' 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.""
I have tried to add mode: "no-cors" to headers but it still didn't worked shows error failed
Possible reasons
1.) Maybe it needs to have the domain name pre-register on phonepe As for example firebase requires some registered domain to have access to its functionalities I have talked to the phonepe team they said for test credentials it should work on any url like localhost or live website
2.) Maybe my code got some error but its the same as on phonepe postman ref "https://developer.phonepe.com/v1/reference/pay-api#pay-request-for-web-flow"(the side postman ALso i used js)

HttpGet method with Http and Https Protocols return response 200 for Https but 404 for Http protocol

Facing a problem with protocols, please find the below code snippet.
If rquestedUrl starts with https, getResponse.getStatusLine().getStatusCode() is returning 200 whereas if the same rquestedUrl starts with http, getResponse.getStatusLine().getStatusCode() is returning 404.
But if I hit through browser I am able to access the requested file in both cases. Could you please let me know what could be the possible problems. (It is used as a filter before calling Orbeon, this is on the process of implementing WSSO.)
System.setProperty("javax.net.ssl.trustStore", "path_to_JKSFile");
System.setProperty("javax.net.ssl.trustStoreType","JKS");
System.setProperty("javax.net.ssl.trustStorePassword","password");
String rquestedUrl = "http://bigminds.web.mindblow.com/project/project1/views/files/Home.xhtml";
HttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet(rquestedUrl);
get.addHeader("Cookie", "somevalues");
get.addHeader("Host", "bigminds.mindblow.com:14325");
HttpResponse getResponse = client.execute(get);
It's likely that the endpoint you are hitting does not accept http requests, all requests must be though https. So there isn't anything wrong with your code, it's just not set up to properly integrate with the site you have there. Looking at the code it looks like you may need to have some type of session (ie: need to login) with the webserver to get the data you want.

Chrome NOT performing a preflight request

I've worked with some previous APIs in AngularJS, however there has always been a preflight using the OPTIONS method. Now I am building a new API from scratch and for some reason, AngularJS does NOT send a preflight request.
From what I have experienced AngularJS always sends a preflight when working with CORS, but not in my case. So question is really, what triggers a preflight in AngularJS if its not request to a domain which is not the same as the one AngularJS is being hosted on?
The example I have is quite easy and looks like this:
$scope.submit = function () {
$http.post('https://slimapi.devz/')
.then(function successCallback(response){
alert(response.data);
}, function errorCallback(response) {
console.log(response);
});
}
The requesting URL is https://slimfrontend.devz/.
Chrome gets triggered by the response headers in the XHR with the POST method, and will not display the result, however, the result is being fetched (as seen in timeline). But again, there is no sign of OPTIONS preflight.
Here is a picture of what my request looks like, and as you can see by the arrow. Chrome does detect the bad match of the origin.
MDN has a good description:
In particular, a request is preflighted if any of the following conditions is true:
(I paraphrase the rest below)
If the request uses any of the following methods (such as PUT)
If particular HTTP headers are set by the JS
If the Content-Type is not a valid value for the enctype attribute of an HTML <form>
IIRC, Angular defaults to sending application/json payloads (which trigger the final condition above).
Your example is of a POST request where you aren't POSTing any data (which is odd) so there is no Content-Type.

API Request Redirect with Response

Say for example I'm try to make a GET Request to www.testjson.com/json, However the response is retrieved from a different domain URL e.g. www.testjson.com/confirmJson.
Does Spring mvc support this, specifically restTemplate.exchange functionality.
I am currently doing this sort of thing, but I am getting an 500 status code (internal server error) and have no way of finding out what exactly is causing the error.
So can RestTemplate actually manage the redirect and provide the necessary JSON response or does it actually wait for the response from the url you provide hence the reason for getting the 500 internal server error?
It is possible to let a RestTemplate automatically follow a redirect.
The server must respond with a Http 3xx and the location header set.
The RestTemplate 'understands' this response and issues a new GET request to the returned location.
This should work with default spring configuration.
See also follow-302-redirect-using-spring-resttemplate

Cross-domain $http request AngularJS

I have simple website I'm building with AngularJS which calls an API for json data.
However I am getting Cross domain origin problem is there anyway around this to allow for cross domain requests?
Error:
XMLHttpRequest cannot load http://api.nestoria.co.uk/api?country=uk&pretty=1&action=search_listings&place_name=soho&encoding=json&listing_type=rent. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost' is therefore not allowed access.
searchByPlaceName: function() {
var url = baseurl+'country=uk&pretty=1&action=search_listings&place_name=london'+encoding+type;
return $http.get(url);
}
It seems that api.nestoria.co.uk does not allow CORS. It has to set the Access-Control-Allow-Origin header itself -- you have no direct control over that.
However, you can use JSONP. That site allows it via the callback query parameter.
$http.jsonp(baseurl+'country=uk&pretty=1&action=search_listings&place_name=london'
+encoding+type + "&callback=JSON_CALLBACK")
Install Fiddler. Add a custom rule to it:
static function OnBeforeResponse(oSession: Session)
{
oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
}
This would allow you to make cross domain requests from localhost. If the API is HTTPS make sure you enable 'decrypt HTTPS traffic' in fiddler.
Reference
-------------------- UPDATE
The response you are getting is JSON. Specifying JSONP as datatype would not work. When you do specify JSONP the return should be a function not JSON object.
JSONP