如何使用axios发送基本身份验证 [英] How to send Basic Auth with axios

查看:1077
本文介绍了如何使用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进行操作时,可以选择设置基本身份验证;如果我不填写这些字段,它也会返回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.

任何想法我在做什么错了吗?

Any ideas what I'm doing wrong?

此处是如何实现此操作的API文档的一部分:

Here is part of the docs of the API of how to implement this:


此服务使用标头中的基本身份验证信息来建立用户会话。凭据针对服务器进行了验证。使用此Web服务将创建一个传递了用户凭据的会话,并返回JSESSIONID。此JSESSIONID可用于后续请求中以进行Web服务调用。*

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.*


推荐答案

基本身份验证有一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆