using php restful webservice in angular JS application

49 views
Skip to first unread message

Raghvendra Naik Gaunkar

unread,
Jun 9, 2014, 8:06:08 AM6/9/14
to ang...@googlegroups.com
I am trying to read JSON data from a PHP Restful web service in my Angular JS application. The web service returns data when hit from the browser, however when executed using http.get method, no data is shown on the HTML page. The developer console shows the error "No 'Access-Control-Allow-Origin' header is present on the requested resource." When goggled I got suggestions saying "add this 'Access-Control-Allow-Origin' header to the web service code". But, can this be achieved from the java script code of angular?

Ian MacLennan

unread,
Jun 9, 2014, 9:14:01 AM6/9/14
to ang...@googlegroups.com
On Monday, 9 June 2014 08:06:08 UTC-4, Raghvendra Naik Gaunkar wrote:
I am trying to read JSON data from a PHP Restful web service in my Angular JS application. The web service returns data when hit from the browser, however when executed using http.get method, no data is shown on the HTML page. The developer console shows the error "No 'Access-Control-Allow-Origin' header is present on the requested resource." When goggled I got suggestions saying "add this 'Access-Control-Allow-Origin' header to the web service code". But, can this be achieved from the java script code of angular?

What you are seeing is your browser rejecting the request because either the hostname, protocol (http vs https) or port of the service you are trying to access is different than the one that is serving your page.  This policy is called CORS.  You need to implement CORS in your service provider (your PHP Restful web service) to tell the browser that it is okay to make cross origin requests to that service.  Your browser will automatically send what is called a 'pre-flight' request using the OPTIONS request method.  It will include an 'Origin' header.  Your web service must handle this options request and send an Access-Control-Allow-Origin header back with either the value of the 'Origin' header or '*'.  It must also return the same header on the actual request.  Otherwise, your Angular application will not be able to see the response of the request.

Before doing this, you should think about which domains should be able to make cross origin requests to your web service layer.  The security implications are touched on briefly in the wikipedia article linked above.

Ian
Reply all
Reply to author
Forward
0 new messages