无效的请求类型 Angular2



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

服务网

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

登录.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')
      );
    }
  }

错误:

正文:"{"错误":"无效的请求类型","状态":"201"}", 状态: 200, 确定:真,状态文本:"正常",

菲律宾语:

<?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 CartUser($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 CartUser($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);
                  });

也许这样事情会为你工作

相关内容

  • 没有找到相关文章

最新更新