Configuration for vue-resource root and authorization

我怕爱的太早我们不能终老 提交于 2019-12-06 11:00:49

问题


I'm looking at the following documentation for vue-resource that describes how to set up configuration: https://github.com/vuejs/vue-resource/blob/master/docs/config.md

It says to set your headers with a common authorization value:

 Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';

I am guessing this "Basic YXBpOnBhc3N3b3Jk" value is just an example, but what is this value for, and what should one use instead of it?

On the same page, I also see a setting for "root":

 Vue.http.options.root = '/root';

I understand this to mean the web URL for the web app. However, why does vue-resource need me to tell it this value? What does it use it for?


回答1:


By adding headers to the Vue.http.headers.common object you are telling vue-resource to add these headers in every request.

You can also add headers to each request:

http({
 url: '/someUrl', 
 method: 'GET',
 headers: {
   Authorization: 'Basic YXBpOnBhc3N3b3Jk'
 }
})

About the value for the Authorization header in the example: It is a base64-encoded string with username/password.

window.atob('YXBpOnBhc3N3b3Jk') // => "api:password"

If you need to use basic authentication when using vue-resource, you should provide your own username/password.

Note that everyone who is using you application can view the username/password. See https://en.wikipedia.org/wiki/Basic_access_authentication for more information about basic authentiaction.

The root-property could be the main endpoint to your REST-service. Instead of:

http({
 url: 'http://api.domain.com/v1/someRoute'
});

You could set the root endpoint with:

Vue.http.options.root = 'http://api.domain.com/v1'

// will call http://api.domain.com/v1/someRoute
http({
 url: '/someRoute'
});



回答2:


If you want set header auth in global way use the inceptor

Vue.http.interceptors.push(function(request, next) {

    request.headers['Authorization'] = 'Basic abcd' //Base64
    request.headers['Accept'] = 'application/json'
    next()
});

and use option credentials:

Vue.http.options.credentials = true;


来源:https://stackoverflow.com/questions/36315389/configuration-for-vue-resource-root-and-authorization

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