在php服务器端Ionic 2 http.post formdata null值

时间:2017-12-07 18:10:34

标签: angular typescript ionic-framework

我使用FormData将数据发送到服务器。我可以登录,但设备和device_token的值在服务器端为空。

以下是代码:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class Auth{

    credentials = {
        username:'',
        password:'',
        token:'',
        device:'ios',
        device_token:'ios'
    }
    headers:any;
    constructor(public http:Http){ 
    }

    Login(credentials)
    {
        let newCredentials: FormData = new FormData();
        newCredentials.append("device",credentials.device);
        newCredentials.append("device_token",credentials.device_token);
        newCredentials.append("username",credentials.username);
        newCredentials.append("password",credentials.password);


        return new Promise((resolve,reject) =>{
            let headers = new Headers();
            headers.append('Content-Type','application/x-www-form-urlencoded');
            console.log("body: "+ "username: " + newCredentials.get("username"));
            console.log("body: "+ "password: " + newCredentials.get("password"));
            console.log("body: "+ "device: " + newCredentials.get("device"));
            console.log("body: "+ "device_token: " + newCredentials.get("device_token"));

            this.headers = {headers}
            this.http.post('http://www.example.com/api/login/',newCredentials,this.headers)
            .map(res => res)
            .subscribe(res=>{
                var resJson = res.json();
                this.credentials.token = resJson.token;
                resolve(res);
            },(err) =>{
                reject(err);
                console.log(err.error);
            });
        });
    }

我尝试使用Postman,服务器上devicedevice_token的值不为空。

1 个答案:

答案 0 :(得分:0)

如果您使用FormData,即使您明确设置了标头,该请求也会自动为multipart/form-data而不是x-www-form-urlencoded。如果您愿意在服务器端处理多部分表单数据,这仍然有效,但除非您上传文件,否则它不是必需的。相反,您可以使用URLSearchParams甚至只使用查询字符串格式化的字符串。

    let newCredentials = new URLSearchParams();
    newCredentials.set("device",credentials.device);
    newCredentials.set("device_token",credentials.device_token);
    newCredentials.set("username",credentials.username);
    newCredentials.set("password",credentials.password);
    newCredentials = newCredentials.toString();

另一方面,你不需要自己将它包装在Promise中。相反,我建议从.http.post

返回可观察流
return this.http.post(...props).map(res => res.json()).map(resJson => {
  this.credentials.token = resJson.token;
  return resJson;
});

现在,您必须在调用.subscribe方法的任何代码中使用auth.Login

如果你真的想使用promises,你也可以在.toPromise()使用this.http.post(),这将执行你的代码现在正在做的事情。