Hapi – 只回复JSON

如何调整Hapi回复函数,使其只回复JSON对象? 我应该把它发送清楚,发送? 我似乎没有find一个好例子

这是一些编辑 – 添加一些示例代码,以了解发生了什么。

路线:

server.route({ method: 'GET', path: '/user/', handler: function (request, reply) { var ids = null; mysqlConnection.query('SELECT ID FROM Users;',function(err,rows,fields){ if(err) throw err; ids = rows; // console.log(ids); reply(ids); }); } }); 

答复:

 <html><head></head><body> <pre style="word-wrap: break-word; white-space: pre-wrap;">[{"ID":1},{"ID":2},{"ID":3},{"ID":4},{"ID":5},{"ID":6},{"ID":7},{"ID":8},{"ID":9},{"ID":10},{"ID":11},{"ID":12},{"ID":13},{"ID":14},{"ID":15},{"ID":16},{"ID":17},{"ID":18},{"ID":19},{"ID":20},{"ID":21}] </pre></body></html> 

我希望我能理解这个问题。 我们在说8.x版吗? 对我来说,它似乎是默认的。 有了这个代码作为路由处理程序,

 folders: { handler: function( request, reply ) { 'use strict'; reply({ folders: folders }).code( 200 ); } }, 

和做

 curl http://localhost:3001/folders 

我得到以下输出

 * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 3001 (#0) > GET /folders HTTP/1.1 > User-Agent: curl/7.37.1 > Host: localhost:3001 > Accept: */* > < HTTP/1.1 200 OK < content-type: application/json; charset=utf-8 < cache-control: no-cache < content-length: 266 < accept-ranges: bytes < Date: Tue, 03 Feb 2015 23:19:31 GMT < Connection: keep-alive < {folders ..... } 

另外请注意,我只调用reply()不能return reply()

HTH

使用hapi的reply(data)和传递一个data对象将为你做的工作。 在内部,hapi将创build适当的JSON数据对象并对其进行响应。

有一个关于如何使用hapi来回复给定请求的JSON的教程,这可能会提供更多的见解。