[关闭]
@xiu-tanwy 2016-11-10T02:40:55.000000Z 字数 1011 阅读 279

NodeJs GET/POST

node


在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交。
表单提交到服务器一般都使用GET/POST请求。
本章节我们将为大家介绍 Node.js GET/POST请求。

获取GET请求内容

由于GET请求直接被嵌入在路径中,URL是完整的请求路径,包括了?后面的部分,因此你可以手动解析后面的内容作为GET请求的参数。
node.js中url模块中的parse函数提供了这个功能。

  1. var http = require('http');
  2. var url = require('url');
  3. var util = require('util');
  4. http.createServer(function(req, res){
  5. res.writeHead(200, {'Content-Type': 'text/plain'});
  6. res.end(util.inspect(url.parse(req.url, true)));
  7. }).listen(3000);

在浏览器中访问http://localhost:3000/v1/api/odds/all?pageIndex=25&email=tanwy.gmail.com 然后查看返回结果:

  1. Url {
  2. protocol: null,
  3. slashes: null,
  4. auth: null,
  5. host: null,
  6. port: null,
  7. hostname: null,
  8. hash: null,
  9. search: '?pageIndex=25&email=tanwy.gmail.com',
  10. query: { pageIndex: '25', email: 'tanwy.gmail.com' },
  11. pathname: '/v1/api/odds/all',
  12. path: '/v1/api/odds/all?pageIndex=25&email=tanwy.gmail.com',
  13. href: '/v1/api/odds/all?pageIndex=25&email=tanwy.gmail.com' }

获取POST请求内容

POST请求的内容全部的都在请求体中,http.ServerRequest并没有一个属性内容为请求体,原因是等待请求体传输可能是一件耗时的工作。
比如上传文件,而很多时候我们可能并不需要理会请求体的内容,恶意的POST请求会大大消耗服务器的资源,所有node.js默认是不会解析请求体的, 当你需要的时候,需要手动来做。这种思路挺好的

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注