Simple request
v.request('get', 'http://example.com', {hello: 'world'}, {})
.then(console.log)
.catch(console.log);
This will perform a request to http://example.com?hello=world
with Accept headers set to application/json. Therefore, the response will be converted to a json object if any. You can overide any previous options passing an object with your custom fetch options.
Convenience methods
You can make use of the convenience methods to perform the request. The default request helper will handle theget, post, put, patch, delete
methods.
v.request.get('http://example.com', {hello: 'world'}, {})
.then(console.log)
.catch(console.log);
Scoped request
You can create another request helper function by calling the new
method of the base request helper. Additionally you can create more request helpers based on a previous created helper inheriting its options like baseUrl and default request options.
let request = v.request.new('http://example.com', {});
request.get('/hello', {hello: 'world'}, {})
.then(console.log)
.catch(console.log);
This will create a request helper pointing to http://example.com
. So, the instruction will perform a request to http://example.com/hello?hello=world
.
Allowed methods
You can create method scoped request helpers by passing an array with the methods
option.
let request = v.request.new('http://example.com', {methods: ['post']});
request.post('/hello', {hello: 'world'}, {})
.then(console.log)
.catch(console.log);
This will create a request helper with only the post
method allowed, so you can safely use this helper without worrying about a wrong use of other methods.
For server side rendering
You can pass within the options object or set manually the urls to handle the requests for server side rendering.v.request.options('urls.node','http://localhost:3000');
v.request.options('urls.api','http://example.com/api');
This will redirect all local requests to http://localhost:3000
. For most of the use cases this will be enough, but for the case where you only use full external urls, you can use the api option to convert this urls to the node version.v.request.get('/hello')
v.request.get('http://example.com/api/hello')
You will need to use the Node plugin for SSR to work.