【问题标题】:Empty $_POST after sending angular post request发送角度发布请求后清空 $_POST
【发布时间】:2018-08-18 23:10:36
【问题描述】:

我正在以角度发送帖子请求

public saveLead(name: string, phone: string, text: string){
        const params: Lead = new Lead(name,phone,text);

        const headers = {
            'Content-Type':'application/x-www-form-urlencoded'
        };

        return this.http.post('http://127.0.0.1/saveLead', params, {headers});
    }

但是当我在 php 端检查 $_POST 时它总是空的

【问题讨论】:

  • 你能登录params吗?里面有什么?
  • 是的,在参数中我有 Lead object Lead {name: "ff", phone: "ff", text: "dd"}
  • 尝试将 Content-Type 更改为 json 为:'Content-Type':'application/json'

标签: angular post http-post


【解决方案1】:

您需要使用HttpParams 来设置您的值

const body = new HttpParams()
  .set('name', 'foo')
  .set('phone', 'bar')
  .set('text', 'baz')

如果您作为正文发送,HttpClient 将处理标题

return this.http.post('http://127.0.0.1/saveLead', body)

【讨论】:

  • 那么这不是你的 API 所期望的x-www-form-urlencoded
【解决方案2】:

在你的 ts 文件中:

public saveLead(name: string, phone: string, text: string){
    const params: Lead = new Lead(name,phone,text);
    return this.http.post('http://127.0.0.1/saveLead', params);
}

在你的 php 中:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$data = json_decode(file_get_contents("php://input"));
var_dump($data)

【讨论】:

  • $data 在这种情况下为 NULL
猜你喜欢
  • 2019-12-04
  • 1970-01-01
  • 2018-07-09
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多