我正在使用IBM Watson工具的音调分析器api。由邮递员测试它工作正常,但在Angular它返回错误为500状态。作为音调分析器api,它需要授权,我将凭证放入标题。
这是我的代码示例。
service.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);
});
}
component.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);
});
由于CORS,您无法从浏览器应用程序直接调用watsonplatform
。 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别名来执行相同的操作。
我确实配置了代理并像你说的那样设置了Api。同时,我编辑了代码并尝试调用该路由,但它返回在控制台中找不到的url 404。
GET http://localhost:4200/watsonplatform/tone-analyzer/api/v3/tone?version=2017-09-21&text=I%27m%20happy 404 (Not Found)
样本如下:
baseUrl ="/watsonplatform/tone-analyzer/api/v3/tone?version=2017-09-21&text=";
constructor(private accountService: AccountService, private toneAnalyser: ToneAnalyserService,
private http:HttpClient) { }
ngOnInit() {
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic fc52487b-f8e5-4948-a11c-43901c0b6a0d:NsP8HyWsoLw8',
'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'
})
};
this.http.get(this.baseUrl+"I'm happy",options).subscribe(data=> {
console.log(data);
});
}