【发布时间】:2016-07-01 01:57:10
【问题描述】:
找不到任何关于此的文档,所以在我深入研究代码之前,有没有人知道在使用 'fetch' (https://github.com/github/fetch) 发出 REST 请求时如何使用基本身份验证。
刚试了下面这行,但是请求中没有设置header:
fetch('http://localhost:8080/timeEntry', {
mode: 'no-cors',
headers: { 'Authorization': 'Basic YW5kcmVhczpzZWxlbndhbGw=' }
})
.then(checkStatus)
.then(parseJSON)
.then(function(activities) {
console.log('request succeeded with JSON response', data);
dispatch(activitiesFetched(activities, null));
}).catch(function(error) {
console.log('request failed', error);
dispatch(activitiesFetched(null, error));
});
用户名和密码是我自己的名字和姓氏,使用curl 可以。
如果我设置了{ 'Accept' : 'application/test' }Accept,就不是Authorization...奇怪了。
为了让我能够继续,我添加了credentials: 'include',它使浏览器提示输入用于与 REST 后端通信的用户名和密码。仅用于测试,将进一步使用 OAuth。
fetch('http://localhost:8080/timeEntry', {
mode: 'no-cors',
credentials: 'include'
})
.then(checkStatus)
.then(parseJSON)
.then(function(activities) {
console.log('request succeeded with JSON response', data);
dispatch(activitiesFetched(activities, null));
}).catch(function(error) {
console.log('request failed', error);
dispatch(activitiesFetched(null, error));
});
【问题讨论】:
-
“身份验证”到底是什么意思?你想做什么?
-
我正在使用 Spring Boot 来公开一个 REST api,它需要基本身份验证,因为我现在已经设置了它。基本上我想做一个“授权:基本 QWxhZGRpbjpPcGVuU2VzYW1l”......但在我自己发送标题之前,我只想检查该功能是否内置在 fetch api 中。
-
据我记忆,基本身份验证只是设置标题,所以它应该像在传递给函数的对象中添加一些一样简单。
标签: javascript rest