调用API METHOD:POST Angular 4.4.7

时间:2018-07-09 18:28:28

标签: angular api post token

我在调用我的服务时遇到问题,我需要使用Basic + Hash for Token来调用API。然后我需要发送所有服务并添加令牌响应。

我有更多从localhost:8080 post消费的服务,并且可以正常使用,该服务已在QA和Developer的服务器中准备就绪,但服务令牌位于服务外部。

我的服务:

 import 'rxjs/add/operator/map';
 import { Observable } from 'rxjs/Rx';
 import { Injectable } from '@angular/core';
 import { environment } from '../../environments/environment';
 import { Http, RequestOptions, Headers } from '@angular/http';

 const newLocal = JSON.stringify({ 'grant_type': 'password', 'username': 
  'user', 'password': 123456 });

 @Injectable()
 export class Service {

 //Token Api

 private urlTokenApi = environment.urlTokenApi;
 getPrueba(): Observable<any>{
  let headers = new Headers();
  headers.append('Authorization', 'Basic hash');
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  headers.append('Access-Control-Allow-Origin', '*');
  let options = new RequestOptions({ headers: headers });
  return this.http.post(this.urlTokenApi, newLocal , options )
  .map(
  (response) => {
    return response;
   }
  ).catch((e: any) => 
     Observable.throw(ServiceErrorsManagement.errorHandler(e)))
   .finally(() => {
      this.onFinally();
    });
 }
}

我的应用程序:

import 'rxjs/add/operator/map';
import { Component, OnInit } from '@angular/core';
import { environment } from '../environments/environment';
import { HttpClient} from '@angular/common/http'
import { Service } from './services/app.services';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[Service]
})

export class AppComponent implements OnInit {

  /* Declaración variables */
  public plamedLogo: String;
  public sanitasLogo: string;
  public sanitasFooter: string;
  private settingsParam = environment.settingsParam;


  /**
   *  Constructor del componente AppComponent.
   */
  constructor(private services : Service) {}

  /**
   * Implementa interface para inicializar valores en las variables.
   */
  ngOnInit(): void {

    this.services.getPrueba().subscribe(
      (response) =>{
        console.log(response);
      },
      (error) =>{
        console.log(error);
      }
    );
  }
}

在导航器中说:

He said Status 200

enter image description here

在consola中:

enter image description here

我需要帮助! :(。

1 个答案:

答案 0 :(得分:1)

在localhost上开发时,这似乎是CORS问题。

您或您的测试人员可以在此处下载允许的CORS chrome插件并打开它。

应该解决CORS错误。

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi