Configuration for vue-resource root and authorizat

2019-04-14 04:43发布

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?

2条回答
The star\"
2楼-- · 2019-04-14 05:17

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'
});
查看更多
戒情不戒烟
3楼-- · 2019-04-14 05:20

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;
查看更多
登录 后发表回答