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

限于喜欢 提交于 2019-12-21 02:35:21

问题


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 just write it in export default {} for every components and it's very bad I know. So I ask you guys to help.

Fixed Thanks to @Hardik Satasiya

~/plugins/axios.js

Every Components:

import axios from 'axios'

var api = axios.create({
  baseURL: 'http://localhost:8000/api/v1/',
  headers: {'Authorization': 'JWT ' + store.state.token}
})

export default api

Issues: Can't tranmit store in to axios.create, so store is not defined


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/48001813/best-way-to-config-global-headers-for-get-post-patch-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!