怎么使用axios发送请求_如何使用Axios发送授权标头

怎么使用axios发送请求

To set headers in an Axios POST request, pass a third object to the axios.post() call.

要在Axios POST请求中设置标头,请将第三个对象传递给axios.post()调用。

You might already be using the second parameter to send data, and if you pass 2 objects after the URL string, the first is the data and the second is the configuration object, where you add a headers property containing another object:

您可能已经在使用第二个参数发送数据,并且如果在URL字符串后传递2个对象,则第一个是数据,第二个是配置对象,在其中添加包含另一个对象的headers属性:

axios.post(url, {
  data: {
    ...
  }
})
axios.post(url, {
  //...data
}, {
  headers: {
    ...
  }
})

To set the authorization header, call it like this:

要设置授权标头,请按以下方式调用它:

const token = '..your token..'

axios.post(url, {
  //...data
}, {
  headers: {
    'Authorization': `Basic ${token}` 
  }
})

(the authorization token might differ, check with the app you’re using)

(授权令牌可能会有所不同,请与您使用的应用程序核对)

To set headers in an Axios GET request, pass a second object to the axios.get() call, for example this is a GitHub GET request to /user:

要在Axios GET请求中设置标头,请将第二个对象传递给axios.get()调用,例如,这是对/user的GitHub GET请求:

axios.get('https://api.github.com/user', {
  headers: {
    'Authorization': `token ${access_token}`
  }
})
.then((res) => {
  console.log(res.data)
})
.catch((error) => {
  console.error(error)
})

I was doing some work with the WordPress API, and I had to authenticate to perform a POST request to a website.

我正在使用WordPress API进行一些工作,并且必须进行身份验证才能对网站执行POST请求。

The easiest way for me was to use basic authentication.

对我而言,最简单的方法是使用基本身份验证。

I was using Axios, so I set the Authorization header to the POST request in this way:

我使用的是Axios,因此我以这种方式将Authorization标头设置为POST请求:

const username = ''
const password = ''

const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')

const url = 'https://...'
const data = {
  ...
}

axios.post(url, data, {
  headers: {
    'Authorization': `Basic ${token}`
  },
})

翻译自: https://flaviocopes.com/axios-send-authorization-header/

怎么使用axios发送请求

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值