0

I'm new in REST API. I'm building up a test environment and trying to make a handshake between Rest API and Client side PHP.

My JSON data is at

http://localhost:50417/api/device

the data is like:

    [
    {"Truck_ID":1,"Company":"Food Mall","Distance":2000},   
    {"Truck_ID":2,"Company":"Food Mall","Distance":4000},
    {"Truck_ID":3,"Company":"Food Mall","Distance":3050}
    ]

I'm trying to act like a client, use PHP to get the data, and put the data in an array. What I tried on client side which is http://localhost:8080 is

<?php
$url = "http://localhost:50417/api/device";
$response = file_get_contents($url);
echo $response;
?>

I also tried js like

<script type="text/javascript">
$(document).ready(function(){
   $.getJSON("http://localhost:50417/api/device",
    function(data){
           alert (data) // this will show your actual json array
      });
    });

</script>

But no matter what I tried, I always get a "No 'Access-Control-Allow-Origin' header is present on the requested resource." What could be the problem? How clients generally get the data from server using REST API? Thank you.

2
  • 1
    Can you view http://localhost:50417/api/device in a browser? JavaScript may give you a Access-Control-Allow-Origin error, but PHP's file_get_contents shouldn't. What error do you get with the PHP code? Commented Sep 3, 2015 at 16:44
  • You are right. PHP can see it. I forgot to delete JS file so I thought it is a problem of CORS. Thank you. Commented Sep 3, 2015 at 17:16

1 Answer 1

3

allow cross origin requests

Enable it in the .htaccess by putting the below line

Header set Access-Control-Allow-Origin "*"

or try from php

<?php
header('Access-Control-Allow-Origin: *');
$url = "http://localhost:50417/api/device";
$response = file_get_contents($url);
echo $response;
?>
Sign up to request clarification or add additional context in comments.

3 Comments

Pretty sure Access-Control-Allow-Origin is a header that's set on the server.
Also, pretty sure PHP doesn't care about the Access-Control-Allow-Origin header sent from the server. It's only JavaScript that cares about CORS requests. He needs to show the PHP error he is getting because it certainly is a different one from the JavaScript.
Rocket Hazmat is right. Thank you guys. I won't consider add an "Access-Control-Allow-Origin" to server. But Feroz gives me an idea to show JSON data without PHP. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.