使用 axios POST 请求传递标头 [英] Passing headers with axios POST request
问题描述
我已经按照 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.
内容类型:'应用程序/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屋!