1

Angular 2 is accessing my php file with this code:

this._http.get('../api/src/1.0/get/images.php').subscribe(res => {
    alert(JSON.stringify(res));
});

Which gives this alert LocalHost:3000 Says

{
    "_body": "<?php\n\nrequire_once '../../orm/connection.php';\n\n$images = R::getAll( 'SELECT * FROM image');\nheader('Content-Type: application/json');\necho json_encode($images);\n\n?>\n",
    "status": 200,
    "statusText": "Ok",
    "headers": {
        "Date": ["Sat",
        " 13 Feb 2016 21:11:26 GMT"],
        "Cache-Control": ["public",
        " max-age=0"],
        "Last-Modified": ["Sat",
        " 13 Feb 2016 20:39:49 GMT"],
        "Accept-Ranges": ["bytes"],
        "ETag": ["W/\"a7-152dc5c6608\""],
        "Content-Length": ["167"],
        "Content-Type": ["application/octet-stream"]
    },
    "type": 2,
    "url": "http://localhost:3000/api/src/1.0/get/images.php"
}

PHP File

<?php

require_once '../../orm/connection.php';

$images = R::getAll( 'SELECT * FROM image');
header('Content-Type: application/json');
echo json_encode($images);

?>

I was expecting the alert to only contain the JSON data. If I go to the file directly via its url it only gives me the JSON data. How would I achieve this?

2 Answers 2

1

You are calling static file at location ../api/src/1.0/get/images.php and you get it's content.

You must run your .php file with server, than call it with http.get(...) You can use php localhost server with php -S localhost:3333 you need to run this command in your project root ( php project )

Sign up to request clarification or add additional context in comments.

5 Comments

So what you are saying is PHP is running localhost default port and Angular 2 is running localhost port 3000 and I need to run php on port 3000? Where would I use php -S localhost:3333 and why 3333?
Ah sorry, it was just example with :3333 you can use any... Best would be to run both client app ( angular 2) and api ( php ) with same server, just in different folders...
Makes sense. Worked fine once I went to the website on my default port!
I have same issue, running app(angular 2) on :3000 and placed php api inside app folder. Can you please suggest where to place php api and run on which port?
and want to post data.
1

From the response you are getting, it looks like you are requesting images.php as "Content-Type":["application/octet-stream"]. Try configuring http.get() to ask for json:

const HEADER = { headers: new Headers({ 'Content-Type': 'application/json' }) };
this._http.get('../api/src/1.0/get/images.php', HEADER).subscribe(res => {
    alert(JSON.stringify(res));
});

1 Comment

Hmm still same with this header

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.