Passing headers with axios POST request

后端 未结 9 1860
青春惊慌失措
青春惊慌失措 2020-11-28 20:27

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

var data = {
    \'key1\': \'val1\',
    \'key2\': \'val2\'
}
ax         


        
相关标签:
9条回答
  • 2020-11-28 20:54

    Or, if you are using some property from vuejs prototype that can't be read on creation you can also define headers and write i.e.

    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");
                    })
                }
            },
    
    0 讨论(0)
  • 2020-11-28 20:55

    This might be helpful,

    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);
     })
    Note: All status codes above 400 will be caught in the Axios catch block. Also, headers are optional for the post method in Axios

    Blockquote

    Blockquote

    0 讨论(0)
  • 2020-11-28 20:55

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

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

    To set headers in an Axios GET request, pass a second object to the axios.get() call.

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

    Cheers!! Read Simple Write Simple

    0 讨论(0)
提交回复
热议问题