轻松创建nodejs服务器(10):处理POST请求

 更新时间:2014年12月18日 11:29:13   投稿:junjie  
这篇文章主要介绍了轻松创建nodejs服务器(10):处理POST请求,本文告诉你如何实现在node.js中处理POST请求,需要的朋友可以参考下

目前为止,我们做的服务器没有实际的用处,接下来我们开始实现一些实际有用的功能。

我们要做的是:用户选择一个文件,上传该文件,然后在浏览器中看到上传的文件。

首先我们需要一个文本区(textarea)供用户输入内容,然后通过POST请求提交给服务器。

我们在start事件处理器里添加代码,requestHandlers.js修改如下:

复制代码 代码如下:

function start(response) {
 console.log("Request handler 'start' was called.");
 var body = '<html>'+ '<head>'+
    '<meta http-equiv="Content-Type" content="text/html; '+
    'charset=UTF-8" />'+
    '</head>'+
    '<body>'+
    '<form action="/upload" method="post">'+
    '<textarea name="text" rows="20" cols="60"></textarea>'+
    '<input type="submit" value="Submit text" />'+
    '</form>'+
    '</body>'+
    '</html>';
 response.writeHead(200, {"Content-Type": "text/html"});
 response.write(body);
 response.end();
}
function upload(response) {
 console.log("Request handler 'upload' was called.");
 response.writeHead(200, {"Content-Type": "text/plain"});
 response.write("Hello Upload");
 response.end();
}
exports.start = start;
exports.upload = upload;

通过在浏览器中访问http://localhost:8888/start就可以看到效果了。

接下来我们要实现当用户提交表单时,触发/upload请求处理程序处理POST请求。

为了使整个过程非阻塞,Node.js会将POST数据拆分成很多小的数据块,然后通过触发特定的事件,将这些小数据块传递给回调函数。这里的特定的事件有data事件(表示新的小数据块到达了)以及end事件(表示所有的数据都已经接收完毕)。

我们通过在request对象上注册监听器(listener) 来实现。这里的 request对象是每次接收到HTTP请求时候,都会把该对象传递给onRequest回调函数。

我们把代码放在服务器里,server.js修改如下:

复制代码 代码如下:

var http = require("http");
var url = require("url");
function start(route, handle) {
 function onRequest(request, response) {
  var postData = "";
  var pathname = url.parse(request.url).pathname;
  console.log("Request for " + pathname + " received.");
  request.setEncoding("utf8");
  request.addListener("data", function(postDataChunk) {
   postData += postDataChunk;
   console.log("Received POST data chunk '"+ postDataChunk + "'.");
  });
  request.addListener("end", function() {
   route(handle, pathname, response, postData);
  });
 }
 http.createServer(onRequest).listen(8888);
 console.log("Server has started.");
}
exports.start = start;

上述代码做了三件事情: 首先,我们设置了接收数据的编码格式为UTF-8,然后注册了“data”事件的监听器,用于收集每次接收到的新数据块,并将其赋值给postData 变量,最后,我们将请求路由的调用移到end事件处理程序中,以确保它只会当所有数据接收完毕后才触发,并且只触发一次。我们同时还把POST数据传递给请求路由,因为这些数据,请求处理程序会用到。

接下来在/upload页面,展示用户输入的内

我们来改一下 router.js:

复制代码 代码如下:

function route(handle, pathname, response, postData) {
 console.log("About to route a request for " + pathname);
 if (typeof handle[pathname] === 'function') {
  handle[pathname](response, postData);
 } else {
  console.log("No request handler found for " + pathname);
  response.writeHead(404, {"Content-Type": "text/plain"});
  response.write("404 Not found");
  response.end();
 }
}
exports.route = route;

然后,在requestHandlers.js中,我们将数据包含在对upload请求的响应中:

复制代码 代码如下:

function start(response, postData) {
 console.log("Request handler 'start' was called.");
 var body = '<html>'+
    '<head>'+
    '<meta http-equiv="Content-Type" content="text/html; '+
    'charset=UTF-8" />'+
    '</head>'+
    '<body>'+
    '<form action="/upload" method="post">'+
    '<textarea name="text" rows="20" cols="60"></textarea>'+
    '<input type="submit" value="Submit text" />'+
    '</form>'+
    '</body>'+
    '</html>';
 response.writeHead(200, {"Content-Type": "text/html"});
 response.write(body);
 response.end();
}
function upload(response, postData) {
 console.log("Request handler 'upload' was called.");
 response.writeHead(200, {"Content-Type": "text/plain"});
 response.write("You've sent: " + postData);
 response.end();
}
exports.start = start;
exports.upload = upload;

我们最后要做的是: 当前我们是把请求的整个消息体传递给了请求路由和请求处理程序。我们应该只把POST数据中,我们感兴趣的部分传递给请求路由和请求处理程序。在我们这个例子中,我们感兴趣的其实只是text字段。

我们可以使用此前介绍过的querystring模块来实现:

复制代码 代码如下:

var querystring = require("querystring");
function start(response, postData) {
 console.log("Request handler 'start' was called.");
 var body = '<html>'+
    '<head>'+
    '<meta http-equiv="Content-Type" content="text/html; '+
    'charset=UTF-8" />'+
    '</head>'+
    '<body>'+
    '<form action="/upload" method="post">'+
    '<textarea name="text" rows="20" cols="60"></textarea>'+
    '<input type="submit" value="Submit text" />'+
    '</form>'+
    '</body>'+
    '</html>';
 response.writeHead(200, {"Content-Type": "text/html"});
 response.write(body);
 response.end();
}
function upload(response, postData) {
 console.log("Request handler 'upload' was called.");
 response.writeHead(200, {"Content-Type": "text/plain"});
 response.write("You've sent the text: "+ querystring.parse(postData).text);
 response.end();
}
exports.start = start;
exports.upload = upload;

好了,以上就是关于处理POST数据的全部内容。

下一节,我们将实现图片上传的功能。

相关文章

  • nodejs对文件中的图片进行归类操作示例

    nodejs对文件中的图片进行归类操作示例

    这篇文章主要为大家介绍了nodejs对文件中的图片进行归类的实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • 切换到淘宝最新npm镜像源的全面指南(支持 Windows、macOS 和多种 Linux 发行版)

    切换到淘宝最新npm镜像源的全面指南(支持 Windows、macOS 和多种 Linux

    在开发过程中,npm 是前端开发者不可或缺的工具,但对于国内的开发者来说,npm 官方源在下载速度上存在一定的瓶颈,本文将详细介绍如何在 Windows、macOS 以及各类 Linux 发行版上切换到淘宝的 npm 镜像源,需要的朋友可以参考下
    2025-03-03
  • 使用puppeteer破解极验的滑动验证码

    使用puppeteer破解极验的滑动验证码

    这篇文章主要介绍了利用puppeteer破解极验的滑动验证功能,基本流程代码实现给大家介绍的非常详细,需要的朋友可以参考下
    2018-02-02
  • 浅谈Node.js中的定时器

    浅谈Node.js中的定时器

    本文给大家分享的是Node.js中的定时器的相关资料,十分的全面细致,有需要的小伙伴可以参考下。
    2015-06-06
  • 前端必会的nodejs知识工具模块使用示例详解

    前端必会的nodejs知识工具模块使用示例详解

    这篇文章主要为大家介绍了前端必会的nodejs知识工具模块使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-10-10
  • nodejs nedb 封装库与使用方法示例

    nodejs nedb 封装库与使用方法示例

    这篇文章主要介绍了nodejs nedb 封装库与使用方法,结合实例形式分析了nodejs nedb.js封装库的定义与使用技巧,需要的朋友可以参考下
    2020-02-02
  • nodejs文件操作模块FS(File System)常用函数简明总结

    nodejs文件操作模块FS(File System)常用函数简明总结

    这篇文章主要介绍了nodejs文件操作模块FS(File System)常用函数简明总结,对FS模块的大部份异步函数做了介绍,而且用中文注释,这下用起来方便了,需要的朋友可以参考下
    2014-06-06
  • NodeJS实现跨域的方法(使用示例)

    NodeJS实现跨域的方法(使用示例)

    CORS是一种 W3C 标准,它使用额外的 HTTP 头来告诉浏览器让运行在一个 origin (domain) 上的Web应用被准许访问来自不同源服务器上的指定的资源,这篇文章主要介绍了NodeJS实现跨域的方法,需要的朋友可以参考下
    2024-05-05
  • nodejs中art-template模板语法的引入及冲突解决方案

    nodejs中art-template模板语法的引入及冲突解决方案

    本篇文章主要介绍了nodejs中art-template模板语法的引入及冲突解决方案,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-11-11
  • Mongoose学习全面理解(推荐)

    Mongoose学习全面理解(推荐)

    本篇文章主要介绍了Mongoose全面理解,详细的介绍了mongoose连接数据库,查找读取数据和数据验证等,有兴趣的可以了解一下。
    2017-01-01

最新评论