[Hapi.js] Replying to Requests

时间:2021-04-10 06:43:05

hapi's reply interface is one of it's most powerful features. It's smart enough to detect and serialize objects, buffers, promises and even streams. This post will demonstrate first hand how to use the reply method to send your data to the client, no matter the format.

'use strict'
const Hapi = require('hapi')
const Boom = require('boom')
const server = new Hapi.Server()
server.connection({ port: 8000 }) server.route({
method: 'GET',
path: '/',
handler: function(request, reply) {
reply() // When called without arguments, Hapi responds with a 200 and empty payload.
// reply(null, 'hello world') // Reply will inspect the first arguments type, only responding with an error if the first argument is in fact an error. Otherwise, it assumes that it should be the response payload. This is not an error
// reply('hello world')
// reply({ hello: 'world' })
// reply(Promise.resolve('hello world'))
// reply(require('fs').createReadStream(__filename))
// reply(new Error('oops')) //If I pass an error object to reply, Hapi will respond to the client with a 500 error.
// reply(Boom.notFound())
}
}) server.start(() => {})