繁体   English   中英

无效的请求类型Angular2

[英]Invalid Request type Angular2

你能告诉我哪里错了吗? 当我使用Postman然后它正在工作。但为什么我不能使用Angular2做同样的事情? 这里的后端api来自PHP.I之前从未使用过PHP后端。这与普通的ASP.net Web Api有什么不同? 我的意思是我们必须发送参数的方式和所有......

Service.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);
  }

}

login.ts

//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')
      );
    }
  }

错误:

body:“{”error“:”无效的请求类型“,”状态“:”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;
 }
}

OP的反馈:我必须像这样使用它。欢呼:)

authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login&username=";

loginUser(username: string, password: string): Observable<any> {
    let headers = new Headers();
    headers.append('content-type', 'application/json');
    let body = '';
    let options = new RequestOptions({ headers: headers });
    let url = this.authenticationEndPoint + encodeURI(username) + '&password=' + encodeURI(password);

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

原答案:

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

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

let body ={
  username:myname,
  password:admin
}

然后发送请求。 它应该将其转换为json并发送。

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

好像你想要使用URLSearchParams ,并将数据发送为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);
}
 //you need to import this
import { Http, Headers, URLSearchParams, Request, RequestOptions, RequestMethod } from '@angular/http';                
                 this.body= {
                  "username":myname,
                  "password":admin
                } //body is defined here
                let headers = new Headers();
                headers.append('HeaderKey', headerValue);


                let options = new RequestOptions({
                  method: RequestMethod.Post,
                  url: this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password),
                  body: this.body,
                  headers: headers
                });
                   //here you are making request 
                this.http.request(new Request(options))
                  .map(res => res.json())
                  .subscribe(data => {
                      //data is fetched
                   if(data.code==200){
                  this.response = data;
                          }
                       else{
                  console.log("some issue with the api response")}
        }, err => {
                    console.log("ERROR!: ", err);
                  });

可能这样事情对你有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM