首页 > 解决方案 > 带有授权的 Angular 5 GET REST Api 返回 stuts 500 内部错误(来自客户端)

问题描述

我正在使用 IBM Watson 工具中的音调分析器 api。当邮递员对其进行测试时,它工作正常,但在 Angular 中,它以 500 状态返回错误。作为音调分析器 api,它需要授权,我将凭据放入标头中。

这是我的代码示例。

服务.ts:

const TONE_API = "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&text=";

const httpOptions = {
  headers: new Headers({
    'Content-Type':  'application/json',
    'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
    'Authorization': 'Basic ************************:************'
  })
};
const options: RequestOptionsArgs = new RequestOptions();
options.headers = httpOptions.headers;

@Injectable()
export class ToneAnalyserService {

  constructor(private http: Http) { }

  // API: GET /message
  getAnalyser(message:string) {
    let url = TONE_API + message;
    return this.http.get(url, options)
      .map(res => res.json())
      .catch(err=>{
        throw(err);
      });
  } 

组件.ts:

 this.message = "I like this idea!"; 
   this.toneAnalyser.getAnalyser(this.message).subscribe(res =>{
     this.result = res;
       console.log(res.json());
      }, err => {
        console.log(err);
      });

标签: angularresttone-analyzer

解决方案


watsonplatform由于 CORS, 您无法直接从浏览器应用程序调用。watsonplatform不支持该政策。

您必须创建自己的后端服务,该服务将代理您的请求。

或者:

对于本地开发,您可以创建proxy.config.js别名:

module.exports = {
  '/watsonplatform': {
    target: 'https://gateway.watsonplatform.net/',
    secure: false,
    changeOrigin: true
  },
};

并从应用程序拨打电话,如get('/watsonplatform/tone-analyzer/api/v3/tone?version=2017-09-21&text=')

当您将托管您的应用程序时,使用 nginx 别名来做同样的事情。


推荐阅读