我的应用程序使用 IBM Watson Speech-to-Text,它需要访问令牌。从命令行我可以使用 curl 获取访问令牌:
curl -X GET --user my-user-account:password \
--output token \
"https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api"
当我使用 Angular 的$http
服务发出 HTTP 请求时,出现 CORS 错误:
var data = {
user: 'my-user-account:password',
output: 'token'
};
$http({
method: 'GET',
url: 'https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api',
data: data,
}).then(function successCallback(response) {
console.log("HTTP GET successful");
}, function errorCallback(response) {
console.log("HTTP GET failed");
});
错误消息说:
请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“ http://127.0.0.1:8080 ”。响应的 HTTP 状态代码为 401。
据我了解,无法从 Angular 执行 CORS;CORS 必须从服务器完成。我知道如何使用 Node 执行 CORS,但我使用 Firebase 作为服务器。
Firebase 有关于使用 CORS 发出 HTTP 请求的文档。文档说要写这个:
$scope.getIBMToken = functions.https.onRequest((req, res) => {
cors(req, res, () => {
});
});
首先,这是行不通的。错误信息是functions is not defined
。显然functions
不在 Firebase 库中?我从index.html
以下位置调用 Firebase :
<script src="https://www.gstatic.com/firebasejs/4.3.0/firebase.js"></script>
我的控制器内喷射的依赖关系$firebaseArray
,$firebaseAuth
和$firebaseStorage
。我是否需要注入依赖项$firebaseHttp
或类似的东西?
其次,如何指定方法('GET')、URL 和数据(我的帐户和密码)?
答案是使用 Cloud Functions for Firebase,它支持从服务器运行 Node 函数。然后使用 Node 模块request
从 Node 发送 HTTP 请求。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句