HttpClient - How post data in a php file in my Ionic Project

Hi, I’ve been trying to use the HttpClient module and it’s working like a charm for get a json file. However, i try to post data in a php script in my ionic project (src/assets/scripts/php/news.php).

src/assets/scripts/news.php :

header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

$postdata = file_get_contents("php://input", true);

src/pages/news/news.ts :slight_smile :

sendNewsToPhp(news: string){
    //let data = JSON.stringify(news);
    let data = news;"../assets/scripts/php/news.php", data, {headers: {'Content-Type': 'application/json'}})
        response => console.log("Res provider :", response),
        error => console.log("err : ", error)

error :

error: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot POST /assets/scripts/php/news.php</pre>\n</body>\n</html>\n"
headers: Object { normalizedNames: Map(0), lazyUpdate: null, lazyInit: lazyInit()
message: "Http failure response for http://localhost:8100/assets/scripts/php/news.php: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:8100/assets/scripts/php/news.php"

I already tried :

I think the problem is that my file is in my ionic project. Is it possible to do that?


You are currently using the 8100 port which is used by ionic to serve your web app. Ionic serve don’t interprate php scripts.

You have to use a http server like apache or nginx configured with php to create your back end logic.
Then your php files will be interpreted and your http serveur will route your request to the right php file on an other port.


Thank you for your reply,

I would like to use only ionic. Do you have an idea for pass data from a ionic page to a script php without pass by an other server ?

You can’t use only ionic.

It’s only an easily way to spin up a development server.
Ionic serve can’t be configured to use php and interprate your php scripts. Anyway you need an other http server to push your application in production environment.


1 Like

What is news.php supposed to actually do?

Take the value in post and write it in a json file + test if a folder exist

Write it where? If on device, you could use the File plugin, but I suspect it would be easier to just use Storage.