See the list of available HTTP methods.
Calling a HTTP methods returns a Promise
that resolves to a Response object or rejects in case of network errors.
You can use methods to convert response stream into usable data:
json
text
formData
arrayBuffer
blob
See ky docs for all available options.
Example: GET JSON data
const package = await $http.$get('https://unpkg.com/nuxt/package.json')
console.log(package.name) // log "nuxt"
In most of the case, you want to get the JSON response. You can use $
prefixed shortcut that smartly parses response using destr.
Alternatively for other response type, you can use the methods mentioned above:
Example: GET data as text
const res = await $http.get('https://unpkg.com/nuxt/package.json')
const responseText = await res.text()
Example: GET data as arrayBuffer
const response = await this.$http.get('https://nuxtjs.org/logos/nuxt.svg')
const buffer = await response.arrayBuffer()
console.log('buffer.byteLength = ', buffer.byteLength)
Example: GET data as readable stream
const response = await this.$http.get('https://example.org')
const reader = response.body.getReader()
let result = ''
reader.read().then(function process ({ done, value }) {
if (done) {
console.log('Stream complete result =>', result)
return
}
const decoder = new TextDecoder('utf-8')
result += decoder.decode(value, { stream: true })
// Read some more, and call this function again
return reader.read().then(process)
})
Example: POST with JSON body
const data = await $http.$post('http://api.com', { foo: 'bar' })
asyncData
For asyncData
and fetch
you can access instance from context:
async asyncData({ $http }) {
const res = await $http.get('https://icanhazip.com')
const ip = await res.text()
return { ip }
}
Example: GET JSON data using $ helper
async asyncData({ $http }) {
const users = await $http.$get('https://reqres.in/api/users')
return { users }
}
When you have access to this
, you can use this.$http
:
methods: {
async fetchSomething() {
this.ip = await this.$http.$get('https://icanhazip.com')
}
}
this
is not available in Nuxt's asyncData
method, see using in asyncData
for how to use this module in asyncData
For store actions you can also use this.$http
:
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$http.$get('https://icanhazip.com')
commit('SET_IP', ip)
}
}
}