从HTML表单将数据发送到Node.js服务器 [英] Send data to Node.js server from HTML form

查看:329
本文介绍了从HTML表单将数据发送到Node.js服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Node.js.

I'm learning Node.js.

我的服务器上有这个

var http = require("http");
var url = require("url");

http.createServer(function(request, response){
    response.writeHead(200, {"Content-Type":"text/plain"});
    var params = url.parse(request.url,true).query;

    console.log(params);

    var a = params.number1;
    var b = params.number2;

    var numA = new Number(a);
    var numB = new Number(b);

    var numOutput = new Number(numA + numB).toFixed(0);

    response.write(numOutput);
    response.end();
}).listen(10000);

这样的URL:localhost:10000/?number1=50000&number2=1在我的浏览器中回显50001,所以它可以工作.

An URL like this: localhost:10000/?number1=50000&number2=1 echoes 50001 on my browser, so it works.

在不使用Express的情况下,我需要使用HTML通过表单发送这两个参数.

Without using Express, I need to send those 2 params through a form using HTML.

如何实现?

推荐答案

简单的答案是 <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.)

这篇关于从HTML表单将数据发送到Node.js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆