在node.js中,如何根据对服务的请求来更改响应?

我有一个在Nodejs中的表单处理程序

function sendToSparkCore(request, response) { parseBody(request,function(body) { var post = { xx: body.switch_value } console.log(post.xx); rx.post( 'https://api.spark.io/v1/devices/01234567/ledFn', { form: { 'access_token' : '987654321', 'params' : post.xx } }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(response); console.log(body); // I want to sen output here } else { console.log('Error encountered'); console.log(response.statusCode); console.log(body); // and here } } ); response.writeHead(200, { 'Content-type': 'text/html; charset=utf-8' }); response.end(newPostFormHTML); }); } 

有没有办法发送输出到函数的响应对象从两条评论线,即成功或失败的职位?

当然你可以

 return response.end(body); 

在if语句中。

上面的代码的问题是,你有响应作为参数,你的sendToSparkCore函数和rx.post的callback。 rx.post响应是从外部作用域中取消响应,所以响应不再是你的节点响应。 只需重命名内部响应参数。