Best way to config Global Headers for Get, Post, Patch in VueJS

后端 未结 2 1616
清歌不尽
清歌不尽 2021-02-04 19:19

I\'m new with VueJs, I\'m finding best way to config Global Headers for Get, Post, Patch in VueJS, which is easy to use and strong security. In the current I ju

相关标签:
2条回答
  • 2021-02-04 19:34

    Yes its good idea to use axios because its repo is maintained.

    you can use global config for this

    import axios from 'axios';
    
    axios.defaults.baseURL = 'https://api.example.com';
    axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    

    OR best way is to create separate instances for this (if you are using multiple api at same time)

    import axios from 'axios';
    
    var myApi = axios.create({
      baseURL: 'https://my-domain.com/api/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'CustomHeader1'}
    });
    
    // another api service
    var amazonApi = axios.create({
      baseURL: 'https://amazon-domain.com/api/',
      timeout: 2000,
      headers: {'X-Custom-Header': 'CustomHeader2'}
    });
    
    export default {
        myApi,
        amazonApi
    }
    

    so you can use api separately without any conflict.

    if you are setting auth header it's nice to not set it at instance creation instead you can set it in your ready callback so you can either fetch from localStorage or obtain from the third party and you can set it.

    to change header afterward after creation

    myApi.defaults.headers.authorization = 'JWT ' + yourToken;
    

    so you can set header from any part when you are sure you have token then you can use this code to set header. And if you have header already from begging you can also use this code to set it.

    0 讨论(0)
  • 2021-02-04 19:39

    You can use vue-resource for making http requests and then use interceptors to modify/patch requests.

    Vue.http.interceptors.push(function(request, next) {
    
      // modify method
      request.method = 'POST';
    
      // modify headers
      request.headers.set('X-CSRF-TOKEN', 'TOKEN');
      request.headers.set('Authorization', 'Bearer TOKEN');
    
      // continue to next interceptor
      next();
    });
    
    0 讨论(0)
提交回复
热议问题