如何将HTTP响应传递给Node.js中的callback?
当从Node查询数据库时,如何将HTTP响应对象传递给asynchronouscallback? 例如(数据库的东西是伪代码):
var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); // read from database: var dbClient = createClient(myCredentials); var myQuery = 'my query goes here'; dbClient.query(myQuery, callback); function callback(error, results, response) // Pass 'response' to the callback? { if (error === null) { for (var index in results) response.write(index); // Error response.end('End of data'); } else { response.end('Error querying database.') } } }).listen(1337, "127.0.0.1");
当传递callback的response
,Node会给出结果继续对象没有方法write
的错误。
这里最好的策略是什么?
通过在callback函数声明中放置响应,您正在创build一个仅在callback函数中具有作用域的新的空响应对象。
相反,您只需要移除响应参数即可。
function callback(error, results) // response is outside of function
在此callback函数中,variables响应现在将引用createServercallback的原始响应variables。 由于此函数位于createServercallback的内部,因此可以访问响应对象。
使用repsonse.send(index)
基本上,你只能打印响应对象,看看里面有什么function。
console.log(response)