如何通过axios调用具有基本权限的远程服务器?



我调用一个基本授权受保护的远程服务器。

axios
.get('http://localhost:9000/posts', {
auth: {
username: 'username'
password: 'password'
}}
)
.then(response => {
console.log(response.data)
})

这行不通。如果设置auth与默认头:

axios.defaults.auth = {username: 'username', password, 'password'}

axios.post('http://localhost:9000/posts', {}, {
headers: { 'Authorization': + 'Basic ' + btoa('username' + ':' + 'password') }
}).then(function(response) {
console.log('Authenticated')
}).catch(function(error) {
console.log('Error on Authentication')
})

他们都不能工作。

从它的请求配置,设置方式是

auth: {
username: 'janedoe',
password: 's00pers3cret'
},

放在哪里?


尝试
axios({
method: 'get',
url: 'http://localhost:9000/posts',
auth: {
username: 'username',
password: 'password'
}
})
.then(response => {
console.log(response.data)
})

也得到错误No 'Access-Control-Allow-Origin' header is present on the requested resource.

axios({
method: 'post',
url: 'http://localhost:9000/posts', 
auth: {
username: 'username',
password: 'password'
}
})

应该工作!查看更多信息。

不确定从问题:你使用令牌或用户名/密码服务器认证?后者的答案在上面。如果您使用令牌,那么试试这个:

const requestOptions = {
...options,
...{
headers: {
authorization: token ? `Bearer ${token}` : ''
}
}
};
axios(url, requestOptions)
.then(res => {
console.log('API call succeeded: ', res); // Read res.data
})
.catch(error => {
if (error)
setError(error.response);
console.log('API call returned an error:', error);
});

至于'Access-Control-Allow-Origin' -这是一个CORS策略错误(https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS),这意味着您正在从不同的域发出请求,而不是您的服务器。这在任何浏览器默认情况下都是不允许的(为了避免黑客攻击…)。你不能在客户身上解决这个问题。这应该在服务器上通过响应API调用来固定,使用额外的HTTP标头集说您的域是允许的(在这里阅读https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin)。

最新更新