Php 无效的请求类型Angular2

Php 无效的请求类型Angular2,php,angular,ionic-framework,ionic2,observable,Php,Angular,Ionic Framework,Ionic2,Observable,你能告诉我哪里错了吗?当我使用邮递员时,它就起作用了。但是为什么我不能用Angular2做同样的事情呢?这里的后端api来自PHP。我以前从未使用过PHP后端。这与普通的ASP.net Web api不同吗?我的意思是我们必须发送参数和所有 服务.ts import { Injectable } from '@angular/core'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; import

你能告诉我哪里错了吗?当我使用邮递员时,它就起作用了。但是为什么我不能用Angular2做同样的事情呢?这里的后端api来自PHP。我以前从未使用过PHP后端。这与普通的ASP.net Web api不同吗?我的意思是我们必须发送参数和所有

服务.ts

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class AuthenticationData {
  authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login";

  constructor(public http: Http) {

  }

  //to login
  loginUser(username: string, password: string): Observable<any> {
    let headers = new Headers();
    headers.append('content-type', 'application/json');

   /*let body = {
     username: username,
     password: password,
   }*/ Not working this too :(

    let body='username=myname&password=admin';//I tried hardcode value.But not working 

    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.authenticationEndPoint, body, options)
      .map(this.extractData)
      .catch(this.handleError);

  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}
//to login
  loginUser(): void {
    if (this.loginForm.valid) {
      this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password).subscribe(
        data => {
          this.response = data;
        },
        err => {
          console.log(err);
        },
        () => console.log('Complete')
      );
    }
  }
错误:

<?php
class ControllerApiLogin extends Controller {
 private $error = array();

 public function index() {
  $json = array();

  if (($this->request->server['REQUEST_METHOD'] == 'POST') && !empty($this->request->get['username']) && !empty($this->request->get['password'])) {

   if(!empty($this->request->get['username']) && !empty($this->request->get['password'])){

    $this->load->language('common/login');

    $this->document->setTitle($this->language->get('heading_title'));

    // User
    $this->registry->set('user', new Cart\User($this->registry));

    if ($this->validate()) {

     $token = token(32);

     $token_count = $this->user->getUniqueToken($token);

     if($token_count==0)
     {
      $this->session->data['token'] = $token; 
     }else{

      $token = token(32);

      $token_count = $this->user->getUniqueToken($token);

      $this->session->data['token'] = $token;  
     }

     $this->load->model('user/user');

     $user_info = $this->model_user_user->getUserByEmail($this->request->get['username']);

     $tokeninfo = array();

     if(count($user_info) > 0){

      $tokeninfo = array(
       'token' => $token,
       'user_id' => $user_info['user_id'],
       'ip'  => $this->request->server['REMOTE_ADDR']
      );

      $date_expired = $this->model_user_user->addUserapitoken($tokeninfo);

     }else{
      $date_expired = '';
     }

     $json['token'] = $token;
     $json['date_expired'] = $date_expired;
     $json['status'] = '200';
    }else{
     $json['error'] = "No match for Username and/or Password.";
     $json['status'] = '201';
    }

   }else{
    $json['error'] = 'Something Went Wrong!!! <br> PLease Enter Correct Login Credentials!!!';
    $json['status'] = '201';
   }

   //$this->response->addHeader('Content-Type: application/json');
   //$this->response->setOutput(json_encode($json));
  }
  else{

    $json['error'] = 'Invalid Request type';
    $json['status'] = '201';
  }
  if (isset($this->request->server['HTTP_ORIGIN'])) {
   $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
   $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
   $this->response->addHeader('Access-Control-Max-Age: 1000');
   $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
  }

  $this->response->addHeader('Content-Type: application/json');
  $this->response->addHeader('HTTP/1.1'.$json['status']);
  $this->response->setOutput(json_encode($json));
 }

 protected function validate() {

  //$this->registry->set('user', new Cart\User($this->registry));

  if (!isset($this->request->get['username']) || !isset($this->request->get['password']) || !$this->user->login($this->request->get['username'], html_entity_decode($this->request->get['password'], ENT_QUOTES, 'UTF-8'))) {
   $this->error['warning'] = $this->language->get('error_login');
  }

  return !$this->error;
 }
}
headers.append('content-type', 'application/json');
let body='username=myname&password=admin';//I tried hardcode value.But not working 
正文:“{”错误“:”无效请求类型“,”状态“:”201“}”,状态:200, ok:true,statusText:“ok”

Php:

<?php
class ControllerApiLogin extends Controller {
 private $error = array();

 public function index() {
  $json = array();

  if (($this->request->server['REQUEST_METHOD'] == 'POST') && !empty($this->request->get['username']) && !empty($this->request->get['password'])) {

   if(!empty($this->request->get['username']) && !empty($this->request->get['password'])){

    $this->load->language('common/login');

    $this->document->setTitle($this->language->get('heading_title'));

    // User
    $this->registry->set('user', new Cart\User($this->registry));

    if ($this->validate()) {

     $token = token(32);

     $token_count = $this->user->getUniqueToken($token);

     if($token_count==0)
     {
      $this->session->data['token'] = $token; 
     }else{

      $token = token(32);

      $token_count = $this->user->getUniqueToken($token);

      $this->session->data['token'] = $token;  
     }

     $this->load->model('user/user');

     $user_info = $this->model_user_user->getUserByEmail($this->request->get['username']);

     $tokeninfo = array();

     if(count($user_info) > 0){

      $tokeninfo = array(
       'token' => $token,
       'user_id' => $user_info['user_id'],
       'ip'  => $this->request->server['REMOTE_ADDR']
      );

      $date_expired = $this->model_user_user->addUserapitoken($tokeninfo);

     }else{
      $date_expired = '';
     }

     $json['token'] = $token;
     $json['date_expired'] = $date_expired;
     $json['status'] = '200';
    }else{
     $json['error'] = "No match for Username and/or Password.";
     $json['status'] = '201';
    }

   }else{
    $json['error'] = 'Something Went Wrong!!! <br> PLease Enter Correct Login Credentials!!!';
    $json['status'] = '201';
   }

   //$this->response->addHeader('Content-Type: application/json');
   //$this->response->setOutput(json_encode($json));
  }
  else{

    $json['error'] = 'Invalid Request type';
    $json['status'] = '201';
  }
  if (isset($this->request->server['HTTP_ORIGIN'])) {
   $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
   $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
   $this->response->addHeader('Access-Control-Max-Age: 1000');
   $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
  }

  $this->response->addHeader('Content-Type: application/json');
  $this->response->addHeader('HTTP/1.1'.$json['status']);
  $this->response->setOutput(json_encode($json));
 }

 protected function validate() {

  //$this->registry->set('user', new Cart\User($this->registry));

  if (!isset($this->request->get['username']) || !isset($this->request->get['password']) || !$this->user->login($this->request->get['username'], html_entity_decode($this->request->get['password'], ENT_QUOTES, 'UTF-8'))) {
   $this->error['warning'] = $this->language->get('error_login');
  }

  return !$this->error;
 }
}
headers.append('content-type', 'application/json');
let body='username=myname&password=admin';//I tried hardcode value.But not working 

OP的反馈:我必须这样使用它。干杯:)

您似乎正在将内容类型设置为json。所以你的身体需要被设置为一个对象。做:

let body ={
  username:myname,
  password:admin
}
然后发送请求。它应该将其转换为json并发送

 return this.http.post(this.authenticationEndPoint, body, options)
      .map(this.extractData)
      .catch(this.handleError);

可能是这样的,事情会对你有用

似乎你想用它来代替,并用
x-www-form-urlencoded
而不是JSON来发送数据。URLSearchParams将像您在硬编码时尝试的那样对参数进行编码,但我认为您的问题是,当您尝试将其作为JSON发送时,请改为以
x-www-form-urlencoded
的形式发送。所以试试这个:

import { URLSearchParams } from '@angular/http';

loginUser(username: string, password: string): Observable<any> {
  let headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  let body = new URLSearchParams();
  body.set('username',username);
  body.set('password',password)

  let options = new RequestOptions({ headers: headers });

  return this.http.post(this.authenticationEndPoint, body.toString(), options)
    .map(this.extractData)
    .catch(this.handleError);
}
从'@angular/http'导入{URLSearchParams};
登录用户(用户名:字符串,密码:字符串):可观察{
let headers=新的headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
let body=新的URLSearchParams();
body.set('username',username);
body.set('password',password)
let options=newrequestoptions({headers:headers});
返回this.http.post(this.authenticationEndPoint,body.toString(),options)
.map(此.extractData)
.接住(这个.把手错误);
}

您是否以json格式接收数据?是的@然后检查我的答案。你是以表单字符串的形式发送。事实上,这是我第一次尝试。它不起作用。这就是为什么我尝试以硬代码值的形式发送。这也不起作用。这是PHP端点。这有什么不同吗?我以前从未使用过PHP后端。没有。。这不会有什么不同。这取决于你的php代码是如何接收请求的。你能把这部分放在问题中吗?你得到的是php格式的表单数据。不是json。。这是symfony吗?我不明白你的意思?请提供更多解释?您已在请求javascript中将contentType设置为“application/json”。在服务器端php中,您正在执行
$this->request->get['password']
。。这是作为键值对接收POST请求。i、 我问它是否是symfony框架