sách gpt4 ăn đã đi

node.js - 请求发射器不会在 Express 中发出 'end'

In lại 作者:搜寻专家 更新时间:2023-11-01 00:33:37 26 4
mua khóa gpt4 giày nike

我遇到请求发射器确实发出“数据”事件但不发出“结束”事件的情况。我不确定如何排除故障。你会怎样?

var Review = require('../lib/review')
, qs = require('querystring');

exports.processReview = function(req, res){
var body = '';
req.setEncoding('utf8');
req.on('data', function(chunk){body += chunk});
req.on('end', function(){
console.log('got here: ' + body);
var obj = qs.parse(body);
var review = new Review({
title: obj.param('title'),
content: obj.param('content'),
submittedBy: obj.param('submittedBy'),
recommendedFor: obj.param('recommendedFor')
});
console.log('New Review: ' + JSON.stringify(review));
res.end('Ok\n');
});
res.end('Ok\n');
console.log('_________end______' + body);
};

exports.displayForm = function(req, res){
var html = 'some head

Review Form

'
+ '
'
+ '

Title:

'
+ '

Content:

'
+ '

Nickname:

'
+ '

Recommended for:

'
+ '

'
+ '
Xem sitemap của VNExpress ';
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(html));
res.end(html);
};

您将如何解决这个问题?问题是什么?谢谢你

câu trả lời hay nhất

如果您正在使用 express 和 bodyParser 或任何类似的中间件,那么 kết thúc 将在它到达您的处理程序之前已经发出。

但是就像我在评论中所说的那样,如果您使用的是 express,那么您也会让事情变得过于艰难。在这种情况下,您不应该nhu cầu担心kết thúc。让中间件负责解析正文。

And by using res.send ,您也可以让 express 处理其他常见任务。 gửi 基本上是 node's kết thúc 的包装器.举几个例子,它:

  • 接受 HTTP 状态、正文或两者作为参数
  • 将对象转换为 json 响应
  • 设置内容长度和其他 header
  • 计算并设置etag
  • 为命中新缓存的请求发送 304
  • 为无形发送发送头部响应

您的处理程序可以这样写:

var Review = require('../lib/review');

exports.processReview = function(req, res){
// the bodyParser (if it is in fact already a middleware) will have parsed
// the request body already into `req.body`
var review = new Review({
title: req.body.title,
content: req.body.content,
submittedBy: req.body.submittedBy,
recommendedFor: req.body.recommendedFor
});
console.log('New Review: ' + JSON.stringify(review));
// here you'd probably save your view before sending.
res.send(200);
};

exports.displayForm = function(req, res){
// here you could keep your html in a template (e.g. /views/form.html), then:
// res.render("form");

// but even without doing that, express handles setting the content-type
// and body length, like so:
var html = 'some head

Review Form

'
+ '
'
+ '

Title:

'
+ '

Content:

'
+ '

Nickname:

'
+ '

Recommended for:

'
+ '

'
+ '
Xem sitemap của VNExpress ';
res.send(html);
};

关于node.js - 请求发射器不会在 Express 中发出 'end',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15853056/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress