离子邮寄请求

时间:2017-10-31 17:43:17

标签: typescript post ionic-framework

下面这段代码向服务器发出了一个帖子请求,但我无法在控制台中看到响应,尽管我可以看到它在服务器日志中执行请求。

 postRequest() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });

    let postParams = {
      username: 'username',
      password: 'password',
    }

    this.http.post("serverurl", postParams, options)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });
  }

代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

尝试记录

console.log(data);
console.log(data.json());
console.log(data.text());

而不是

console.log(data['_body']);

答案 1 :(得分:0)

终于找到了解决方案!我已经拆分了代码:

<强>提供商

  makeLogin(email: string, password: string) 
  {       
      let urlSearchParams = new URLSearchParams();
      urlSearchParams.append('username', email);
      urlSearchParams.append('password', password);
      let body = urlSearchParams.toString()

      var headers = new Headers();
      headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

      return this.http
          .post('https://classevivaapi.herokuapp.com/voti', body, { headers: headers })
          .map(response => response.json())
  }

离子页面

    postRequest() {
      var email = 'andreademasi80@gmail.com';
      var password = 'Andrea99';

      this.api.makeLogin(email, password)
          .subscribe((response) => {
              alert(response);
          }, (error) => {
              alert(error);
          });
    }

我还必须修改我的API以允许跨源资源共享(CORS)