Angular/HttpClient - 如何在我的 Ionic 项目中 post 文件中的 php 数据

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

我一直在尝试使用 HttpClient 模块,它的工作原理非常适合获取 json 文件。但是,我尝试在我的离子项目 (src/assets/scripts/php/news.php).

的 php 脚本中 post 数据

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;
this.http.post("../assets/scripts/php/news.php", data, {headers: {'Content-Type': 'application/json'}})
  .subscribe(
    response => console.log("Res provider :", response),
    error => console.log("err : ", 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"

我已经试过了:

http://localhost:8100/assets/scripts/php/news.php
http://myip:8100/assets/scripts/php/news.php

我认为问题是我的文件在我的 ionic 项目中。可以吗?

要知道 -> 我无法使用 url.

访问我的 php 文件

我想你在那里误会了。 PHP 在 80 端口而不是 ionic 服务端口处理 Apache/Ngix 服务,你认为对吗? 事实上,我们通常有一个单独的 web 服务作为数据提供者,所以我们的请求 url 经常像 this.http[get/post/put/delete]('http://server.domain/api/your-page.php', data) 您可以通过代理部分更新 angular 配置 slove 它,但代理设置在将其打包到 App 后看起来不起作用,所以我的代码在发送之前更新 url = baseUrl + url;