ionic2不发送帖子数据

时间:2017-08-18 13:22:39

标签: angular ionic2

以下是我的auth.service.ts中的一个函数我从其中一个页面调用它..

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Storage } from '@ionic/storage';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {

  public token: any;

  constructor(public http: Http, public storage: Storage) {

  }
login(credentials){

return new Promise((resolve, reject) => {
    console.log(credentials);
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.post('https://mysite.co.uk/ionlogin.php', JSON.stringify(credentials), {headers: headers})
      .subscribe(res => {

        let data = res.json();
        this.token = data.token;
        this.storage.set('token', data.token);
        resolve(data);

        resolve(res.json());
      }, (err) => {
        reject(err);
      });

});

}
}

上述登录功能成功调用,但不发送任何数据。但是在控制台中,console.log(凭证)在发布请求之前打印。

  

{email:" sugumar",密码:" 123456"}

但是在浏览器的网络标签中,我看不到发送到服务器的任何数据。

并在我使用

打印的服务器中
  

的var_dump(json_decode(的file_get_contents(" PHP://输入&#34)));

它在浏览器的网络选项卡中输出null

我还在控制台中看到以下错误

XMLHttpRequest无法加载https://mysite.co.uk/ionlogin.php。在预检响应中,Access-Control-Allow-Header不允许使用请求标题字段Access-Control-Allow-Origin。

所以我在php

中添加了以下几行
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, 
    X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");

但仍然是同样的问题

1 个答案:

答案 0 :(得分:1)

尝试使用RequestOptions而不是直接将标题作为对象发送

import { Http, Headers, RequestOptions } from '@angular/http';

public login = () => {
  return new Promise((resolve, reject) => {
    let headers = new Headers({'Content-Type', 'application/json'});
    // JUST TOOK OFF APPEND CAUSE I LIKE THIS WAY, THERE'S NO NEED FOR YOU TO REMOVE IT.
    let options = new RequestOptions({headers: headers});
    this.http.post('https://mysite.co.uk/ionlogin.php', JSON.stringify(credentials), options)
    .subscribe(res => {

      let data = res.json();
      this.token = data.token;
      this.storage.set('token', data.token);

      // WHY DO YOU RESOLVE THIS TWICE? IT'LL ONLY GET THE FIRST RESOLVE
      resolve(data);
      resolve(res.json());
    }, (err) => {
      reject(err);
    });
  });
}

RequestOptions模块基于请求的获取规范创建您的选项,可能只是传递标题,因为对象使其失败或者请求选项提供的内容缺失。

希望这有帮助。