【问题标题】:How, in Node.js, to respond to a GET request from client (send some HTML in response)?在 Node.js 中,如何响应来自客户端的 GET 请求(发送一些 HTML 作为响应)?
【发布时间】:2013-06-11 07:40:52
【问题描述】:

我有一个 Node.js 应用程序,除其他外,它通过将一些 HTML 发送回该页面来响应来自网页的 AJAX (jQuery) $.get() 请求。该应用使用 Express。

所以在服务器代码中,我有:

app.get('/friends', api.friends);,其中api 定义为api = require('./static/routes/api'),我设置的是app.use(app.router);

在我的api.js 模块中,我有api.friends 代码:我有

exports.friends = function(request, response) { ...lots of code... };

我在其中创建了一些特定的 HTML。

现在,我的问题是:我如何真正将这个 HTML 发送回客户端?我不能使用传入的response 对象,因为这不再是Express 类型的response 对象,所以通常的reponse.send().end() 等方法不存在。

我不知道该怎么做,这反映了对 Node 及其内部结构缺乏了解(这是我的第一个 Node 应用程序),因此我们将非常感谢和欢迎任何和所有帮助。谢谢。

【问题讨论】:

  • 为什么response不再是一个Express对象?

标签: ajax node.js get express


【解决方案1】:

正如@Daniel 在他的评论中所说,response 对象肯定是一个 Express 对象,您可以简单地通过 rendering 一个视图返回您的 HTML,如下所示:

exports.friends = function(request, response) {
   //do stuff
   response.render('friends.html');
 };

当然,您必须在 app.js 设置中定义视图,如下所示:

app.set('views', __dirname + '/views')

【讨论】:

  • 嗯,我也是这么想的。当我运行我的应用程序时,我得到的错误是:**.../static/routes/api.js:29 response.render(table);****TypeError: Object #<IncomingMessage> has no method 'render'** at Request.exports.friends [as _callback] at Request.init.self.callback at Request.EventEmitter.emit at Request.onResponseat Request.EventEmitter.emit at IncomingMessage.Request.onResponse.buffer at IncomingMessage.EventEmitter.emit at IncomingMessage._emitEnd at HTTPParser.parserOnMessageComplete [as onMessageComplete] at CleartextStream.socketOnData
【解决方案2】:

啊!我真是个白痴!在我的exports.friends 处理程序中,有一个request 发出,作为其调用参数的一部分,它采用function(error, response, body) 形式的函数。注意 response 参数。我在 within 这个函数中发送了结果,它当然使用了这个response 对象,而不是通过exports.friends(request, response) 传递的那个。多哈。哦,好吧 - 无论如何谢谢 - 你让我再次查看代码,并且知道response 对象是合法的,我能够看到错误。再次感谢您 - 非常感谢!

【讨论】:

  • 不客气。使用exports.friend 中的一些代码编辑您的问题可能是个好主意,作为该问题未来访问者的参考。
猜你喜欢
  • 2018-10-12
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
  • 1970-01-01
  • 2019-05-31
  • 1970-01-01
相关资源
最近更新 更多