Ionic 2 http.post登录

时间:2017-04-06 09:52:58

标签: http post ionic2

我正在尝试在离子2应用程序中转换离子应用程序并尝试重新制作登录进度。 我在我的离子2应用程序中写了这个:

  loginUser(){
      localStorage.setItem('username', this.username);
      localStorage.setItem('password', this.password);
      localStorage.setItem('company', this.company);

        this.loginData = {};
        this.loginData.UserID = this.username;
        this.loginData.CompanyID = this.company;
        this.loginData.Password = this.password;


      let body = {"jsonLogin": JSON.stringify(this.loginData)}
      let link = 'working link';
      let headers = new Headers({
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      });
      let options = new RequestOptions({headers: headers});

      this.http
          .post(link, body, options)
          .map(res => res.json())
          .subscribe(
              data => {
              console.log(data);
               //this.navCtrl.push(MenuPage);
          }, err => {
              console.log(err);
          });
   }

在离子1应用程序中,这是代码:

$scope.loginUser = function () {
        json = {};
        json.UserID = $scope.data.username;
        json.CompanyID = $scope.data.company;
        json.Password = $scope.data.password;

        $http({
            method: 'POST',
            data: {
                "jsonLogin": JSON.stringify(json)
            },
            url: 'working link',
            transformRequest: function (obj) {
                var str = [];
                for (var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
        }

我的问题是在POST中,当我使用离子2应用程序的代码发布时,这就是我的表单数据:

{
"jsonLogin": "{\"UserID\":\"admin\",\"CompanyID\":\"test\",\"Password\":\"pass\"}"
}:

虽然离子1 app Form Data看起来像这样:

jsonLogin:{"UserID":"admin","CompanyID":"test","Password":"pass"}

POST正在运行,因为我从服务器收到错误消息,我只是不知道如何格式化数据以执行正确的POST。

提前感谢您的帮助。

修改 通过添加新标题来实现它:

let headers = new Headers({
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': '*/*'
      });

并发送硬编码字符串:

createStringForLogin(username: any, company: any, password: any){
         return 'jsonLogin={"UserID":"'+username+'","CompanyID":"'+company+'","Password":"'+password+'"}';
  }

1 个答案:

答案 0 :(得分:1)

我认为

let body = {"jsonLogin": this.loginData};

应该解决你的问题。如果它不起作用,请告诉我。

另外,如果您在将参数设置为this.loginData时遇到问题。像这样设置它们:

this.loginData = {};
this.loginData['UserID'] = this.username;
this.loginData['CompanyID'] = this.company;
this.loginData['Password'] = this.password;