通过axios POST请求传递标头 [英] Passing headers with axios POST request

查看:959
本文介绍了通过axios POST请求传递标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按照npm软件包文档中的建议编写了axios POST请求:

I have written an axios POST request as recommended from the npm package documentation like:

var data = {
    'key1': 'val1',
    'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data)       
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

它可以工作,但是现在我修改了后端API以接受标头.

And it works, but now I have modified my backend API to accept headers.

Content-Type:'application/json'

Content-Type: 'application/json'

授权:"JWT fefege ..."

Authorization: 'JWT fefege...'

现在,此请求在Postman上运行良好,但是在编写axios呼叫时,我遵循 此链接 ,并且无法完全正常工作.

Now, this request works fine on Postman, but when writing an axios call, I follow this link and can't quite get it to work.

我不断收到400 BAD Request错误.

这是我的修改请求:

axios.post(Helper.getUserAPI(), {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'JWT fefege...'
    },
    data
})      
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

非常感谢您的帮助.

推荐答案

使用axios时,为了传递自定义标头,请提供一个包含标头的对象作为最后一个参数

When using axios, in order to pass custom headers, supply an object containing the headers as the last argument

修改您的axios请求,例如:

Modify your axios request like:

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'JWT fefege...'
}

axios.post(Helper.getUserAPI(), data, {
    headers: headers
  })
  .then((response) => {
    dispatch({
      type: FOUND_USER,
      data: response.data[0]
    })
  })
  .catch((error) => {
    dispatch({
      type: ERROR_FINDING_USER
    })
  })

这篇关于通过axios POST请求传递标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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