问题
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