如何使用 axios 发送基本身份验证 [英] How to send Basic Auth with axios
问题描述
我正在尝试实现以下代码,但有些东西不起作用.代码如下:
I'm trying to implement the following code, but something is not working. Here is the code:
var session_url = 'http://api_address/api/session_endpoint';
var username = 'user';
var password = 'password';
var credentials = btoa(username + ':' + password);
var basicAuth = 'Basic ' + credentials;
axios.post(session_url, {
headers: { 'Authorization': + basicAuth }
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
它返回 401 错误.当我使用 Postman 时,有一个选项可以设置 Basic Auth;如果我不填写这些字段,它也会返回 401,但如果我填写,则请求成功.
It's returning a 401 error. When I do it with Postman there is an option to set Basic Auth; if I don't fill those fields it also returns 401, but if I do, the request is successful.
知道我做错了什么吗?
这里是 API 文档的一部分,说明了如何实现:
Here is part of the docs of the API of how to implement this:
此服务使用标头中的基本身份验证信息来建立用户会话.凭据针对服务器进行验证.使用此 Web 服务将使用传递的用户凭据创建会话并返回 JSESSIONID.此 JSESSIONID 可用于后续请求以进行网络服务调用.*
This service uses Basic Authentication information in the header to establish a user session. Credentials are validated against the Server. Using this web-service will create a session with the user credentials passed and return a JSESSIONID. This JSESSIONID can be used in the subsequent requests to make web-service calls.*
推荐答案
Basic Auth 有一个auth"参数:
There is an "auth" parameter for Basic Auth:
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
来源/文档:https://github.com/mzabriskie/axios
示例:
await axios.post(session_url, {}, {
auth: {
username: uname,
password: pass
}
});
这篇关于如何使用 axios 发送基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!