简体   繁体   中英

Empty $_POST after sending angular post request

I am sending post request in angular

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});
    }

but when I am checking $_POST on php side it is always empty

You need to use the HttpParams to set your values

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

and that you send as body, HttpClient will take care of the headers

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

in your ts file:

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);
}

in your 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM