使用axios POST请求传递标头[ReactJS]

时间:2017-06-18 17:45:29

标签: reactjs redux react-redux axios

我已根据npm包文档中的建议编写了一个axios POST请求,如

 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以接受标题

  

Content-Type:'application / json'

     

授权:'JWT fefege ......'

现在这个请求在POSTMAN上运行正常,但在编写axios调用时,我会按照 this link 进行操作。

我正在获得400 BAD Request error

这是我修改过的请求

  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})
            })

任何帮助都会得到极大的赞赏

提前致谢。

11 个答案:

答案 0 :(得分:94)

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

修改你的axios请求,如

   $pwrurl = "www.*****.com/reset_password.php?q=".$*****;
    $emailto = '$useremail';
    $toname = '$username';
    $emailfrom = 'hello@****.com';
    $fromname = '****';
    $subject = 'Password Change Request';
    $messagebody = 'Dear '.$name.'<br/><br/>We received a request to reset the <b> login password  </b> of your account. <br/>If you have not made the request, please call us immediately as someone else might be trying to access your account. <br> If you have indeed requested the reset, please click on the following link to reset your login password: <br/>'.$pwrurl.'</br>Remeber the link will remain active for an hour.<br/><b/r><b><i>****</b></i>';

    $headers = 
        'Return-Path: ' . $emailfrom . "\r\n" . 
        'From: ' . $fromname . ' <' . $emailfrom . '>' . "\r\n" . 
        'X-Priority: 3' . "\r\n" . 
        'X-Mailer: PHP ' . phpversion() .  "\r\n" . 
        'Reply-To: ' . $fromname . ' <' . $emailfrom . '>' . "\r\n" .
        'MIME-Version: 1.0' . "\r\n" . 
        'Content-Transfer-Encoding: 8bit' . "\r\n" . 
        'Content-Type: text/html; charset=iso-8859-1' . "\r\n";
        $params = '-f ' . $emailfrom;
   $test = mail($emailto, $subject, $messagebody, $headers, $params);

答案 1 :(得分:17)

以下是带有自定义标题的axios.post请求的完整示例

&#13;
&#13;
var postData = {
  email: "test@test.com",
  password: "password"
};

let axiosConfig = {
  headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "Access-Control-Allow-Origin": "*",
  }
};

axios.post('http://<host>:<port>/<path>', postData, axiosConfig)
.then((res) => {
  console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
  console.log("AXIOS ERROR: ", err);
})
&#13;
&#13;
&#13;

答案 2 :(得分:7)

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

const token = '..your token..'

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

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

const token = '..your token..' 

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

干杯!!读取简单写入简单

答案 3 :(得分:2)

您还可以使用拦截器传递标头

它可以为您节省很多代码

axios.interceptors.request.use(config => {
  if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

  const accessToken = AuthService.getAccessToken();
  if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;

  return config;
});

答案 4 :(得分:2)

我们可以将标头作为参数传递,

  onClickHandler = () => {
    const data = new FormData() 
    for(var x = 0; x<this.state.selectedFile.length; x++) {
      data.append('file', this.state.selectedFile[x])
    }

    const options = {
      headers: {
          'Content-Type': 'application/json',
      }
    };
    
    axios.post("http://localhost:8000/upload", data, options, {
      onUploadProgress: ProgressEvent => {
        this.setState({
          loaded: (ProgressEvent.loaded / ProgressEvent.total*100),
        })
      },
    })
      .then(res => { // then print response status
        console.log('upload success')
      })
      .catch(err => { // then print response status
        console.log('upload fail with error: ',err)
      })
    }

答案 5 :(得分:1)

Shubham的答案对我不起作用。

在使用axios库并传递自定义标头时,需要将标头构造为键名称为“ headers”的对象。标头键应包含一个对象,这里是Content-Type和Authorization。

下面的示例工作正常。

    var 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})
        })

答案 6 :(得分:1)

这可能会有所帮助,

const data = {
  email: "me@me.com",
  username: "me"
};

const options = {
  headers: {
      'Content-Type': 'application/json',
  }
};

axios.post('http://path', data, options)
 .then((res) => {
   console.log("RESPONSE ==== : ", res);
 })
 .catch((err) => {
   console.log("ERROR: ====", err);
 })
注意:所有高于400的状态代码将被Axios捕获块捕获。 此外,标头对于Axios

中的post方法是可选的
  

Blockquote

Blockquote

答案 7 :(得分:1)

axios.post可以接受3个参数,最后一个参数可以接受可以设置标题的 config 对象

示例代码与您的问题:

{{1}}

答案 8 :(得分:0)

Json必须使用双引号格式化

赞:

headers: {
                "Content-Type": "application/Jason",
                "Authorization": "JWT fefege..."
            }

不仅仅是:

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

答案 9 :(得分:0)

或者,如果您正在使用vuejs原型中的某些属性,这些属性在创建时无法读取,则您还可以定义标头并进行写操作。

storePropertyMaxSpeed(){
                axios.post('api/property', {
                    "property_name" : 'max_speed',
                    "property_amount" : this.newPropertyMaxSpeed
                    },
                    {headers :  {'Content-Type': 'application/json',
                                'Authorization': 'Bearer ' + this.$gate.token()}})
                  .then(() => { //this below peace of code isn't important 
                    Event.$emit('dbPropertyChanged');

                    $('#addPropertyMaxSpeedModal').modal('hide');

                    Swal.fire({
                        position: 'center',
                        type: 'success',
                        title: 'Nova brzina unešena u bazu',
                        showConfirmButton: false,
                        timer: 1500
                        })
                })
                .catch(() => {
                     Swal.fire("Neuspješno!", "Nešto je pošlo do đavola", "warning");
                })
            }
        },

答案 10 :(得分:0)

拦截器

我遇到了同样的问题,原因是我没有在拦截器中返回响应。 Javascript正确地这样认为,我想返回undefined作为承诺:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });