angular - 带有授权的 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);
});
解决方案
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 别名来做同样的事情。
推荐阅读
- excel - 我的 excel 文件是德国(德语)格式,想更改为英语(英国)格式
- php - Symfony 也许你忘记在实体管理器中持久化它了?
- excel - 为什么我的程序在 Excel 打印输出方面无法在其他计算机上运行
- groovy - Groovy:如何手动创建日期?- GroovyRuntimeException
- kubernetes - Pod 被“节点资源不足:inode”杀死,但 df -i 仅显示 29% 的使用率
- docker - 倍福 TwinCat3 CI/CD Docker
- javascript - 了解函数绑定
- python - 将 2 个 Python 文件转换并合并为一个 exe 不起作用
- c# - 如何访问 ItemsPanelTemplate 中的 ItemsWrapGrid 面板?
- jenkins-pipeline - 出现错误:脚本在测试时返回退出代码 1