且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从HTML表单将数据发送到Node.js服务器

更新时间:2023-11-09 12:04:16

简单的答案是 <form method="get"> .浏览器会将表单数据转换为您已经在处理的查询字符串参数.

The simple answer is <form method="get">. The browser will turn the form data into query string parameters that you're already handling.

如果需要POST,则将HTML表单发布为请求实体正文.在节点中,每当主体的一部分到达服务器时,ClientRequest(在您的示例中为request变量)都会发出data事件. 您不会一次收到整个正文.您必须缓冲直到收到整个正文,然后解析数据.

If you need to POST, HTML forms are posted as the request entity-body. In node, a ClientRequest (the request variable in your example) emits a data event every time a chunk of the body arrives at the server. You will not receive the entire body at once. You must buffer until you've received the entire body, then parse the data.

由于分块与普通Transfer-Encoding之类的事情以及浏览器提交表单数据的方式不同,这很难解决.我只使用可仿(无论如何Express都会在后台使用),或者至少如果您绝对必须实施自己的文章,请研究它如何处理表单帖子. (实际上,这样做只是出于教育目的-我不能太强调您应该对可能会在生产中使用的任何东西使用强大的功能.)

This is hard to get right because of things like chunked vs normal Transfer-Encoding and the different ways browsers can submit form data. I'd just use formidable (which is what Express uses behind the scenes anyway), or at least study how it handles form posts if you absolutely must implement your own. (And really, do this only for educational purposes – I can't stress enough that you should use formidable for anything that might end up in production.)