如何在React中使用axios将标头添加到post API中?

时间:2019-10-02 13:43:30

标签: reactjs request axios

我正在尝试使用axios创建一个post API。我有一个带有axios语法的组件:

export function postAPI(callback, url, body) {    
    axios.post(url, body, { headers: { 'Key': '*******'}})
        .then(res => callback({ data: res.data, isLoading : false }))
        .catch(err => callback({ error: err, isLoading : false }));
}

我正在做这样的请求:

 postAPI(result => {
     const { data, error } = result;

     if (error) {
           alert('error')    
     }
     if (data) {
           alert('success')
      }
 }, URL, body });

目标: 我还有其他帖子请求,必须再有一个标头,但在这种情况下我不知道该怎么做...

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

也许是这样

export function postAPI(callback, url, body, additionalHeaders) {    
    let headers = [{ 'Key': '*******'}];
    if (additionalHeaders) {
      headers = [...headers, ...additionalHeaders];
    }
    axios.post(url, body, { headers })
        .then(res => callback({ data: res.data, isLoading : false }))
        .catch(err => callback({ error: err, isLoading : false }));
}

 postAPI(result => {
     const { data, error } = result;

     if (error) {
           alert('error')    
     }
     if (data) {
           alert('success')
      }
 }, URL, body, [{'Content-Type': 'application/json'}] });