http://blog.csdn.net/puncha/article/details/9015317

Nodejs 发送HTTP POST请求实例

2013-06-03 17:55 71745人阅读 评论(3) 收藏 举报
 分类:
JavaScript(26)  Node.js(44) 

版权声明:本文为博主原创文章,未经博主允许不得转载。

项目里面需要用到使用NodeJs来转发HTTP POST请求,研究了很久最后才弄通,把过程记录一下:

接收端代码很简单,就是回送body.address属性:

  1. exports.sendEmail = function (req, res) {
  2. res.send(200, req.body.address);
  3. }

之所以能够访问body的address属性,这得益于express.js(connect)的bodyparser中间件。该中间件解析request的body,假如其content type满足某些条件的话,就尝试将其转换成javascript对象。某些条件是指:multipart, urlencoded, json。

好了,接下来看转发端的代码,为了简单起见,我直接将hard-coding的数据进行转发:

  1. exports.sendEmail = function (req, res) {
  2. var data = {
  3. address: 'test@test.com',
  4. subject: "test"
  5. };
  6. data = require('querystring').stringify(data);
  7. console.log(data);
  8. var opt = {
  9. method: "POST",
  10. host: "localhost",
  11. port: 8080,
  12. path: "/v1/sendEmail",
  13. headers: {
  14. "Content-Type": 'application/x-www-form-urlencoded',
  15. "Content-Length": data.length
  16. }
  17. };
  18. var req = http.request(opt, function (serverFeedback) {
  19. if (serverFeedback.statusCode == 200) {
  20. var body = "";
  21. serverFeedback.on('data', function (data) { body += data; })
  22. .on('end', function () { res.send(200, body); });
  23. }
  24. else {
  25. res.send(500, "error");
  26. }
  27. });
  28. req.write(data + "\n");
  29. req.end();
  30. }

这里浏览器回显的就是"test@test.com",注意,我把content type设置成x-www-form-urlencoded,这是bodyparser所支持的了类型之一,而body的格式通过require('querystring').stringify(...)来格式化的,这个会将对象转换成诸如"address=test%40test.com&subject=test"这种格式的字符串。

再来看另外一种content type,JSON:

  1. exports.sendEmail = function (req, res) {
  2. var data = {
  3. address: 'test@test.com',
  4. subject: "test"
  5. };
  6. data = JSON.stringify(data);
  7. console.log(data);
  8. var opt = {
  9. method: "POST",
  10. host: "localhost",
  11. port: 8080,
  12. path: "/v1/sendEmail",
  13. headers: {
  14. "Content-Type": 'application/json',
  15. "Content-Length": data.length
  16. }
  17. };
  18. var req = http.request(opt, function (serverFeedback) {
  19. if (serverFeedback.statusCode == 200) {
  20. var body = "";
  21. serverFeedback.on('data', function (data) { body += data; })
  22. .on('end', function () { res.send(200, body); });
  23. }
  24. else {
  25. res.send(500, "error");
  26. }
  27. });
  28. req.write(data + "\n");
  29. req.end();
  30. }

这同样能成功,但是有2个修改,一个是我用JSON.stringify()来格式化body内容,另一个是我把content type变成了json格式,当然,这个也是body parser所支持的格式之一!

另外,有两个地方,我不是很清楚,一个是貌似content-length不是必须的,另一个是req.write(data+"\n")的"\n"也不是必须的,这个有待研究。。。

补充:

bodyparser的代码在”\node_modules\express\node_modules\connect\lib\middleware\bodyParser.js“,它其实什么都没做,只是把解析body的任务派发给了另外3个中间件:./multipart, ./urlencoded, ./json:

  • ./multipart 负责 multipart/form-data 类型。
  • ./urlencoded 负责 application/x-www-form-urlencoded 类型。
  • ./json 负责 application/json 类型。

nodejs的POST请求的更多相关文章

  1. nodejs接收post请求参数

    原文 https://blog.csdn.net/u013263917/article/details/78682270#1.2 nodejs接收post请求参数1.1-浏览器发送post请求参数的方 ...

  2. nodejs模仿http请求组件nodegrass简单例子

    1.搭建nodejs环境. 2.执行npm install nodegrass命令. 3.引入模块,var ng= require(nodegrass); 4.下面先看nodegrass底层的get方 ...

  3. nodejs发起HTTPS请求并获取数据

    摘要:在网站中有时候需要跨域请求数据,直接用Ajax无法实现跨域,采用其他方式需要根据不同的浏览器做相应的处理.用Nodejs可以很好的解决这些问题,后台引用HTTPS模块,发送和返回的数据均为JSO ...

  4. Nodejs发送Post请求时出现socket hang up错误的解决办法

    参考nodejs官网发送http post请求的方法,实现了一个模拟post提交的功能.实际使用时报socket hang up错误. 后来发现是请求头设置的问题,发送选项中需要加上headers字段 ...

  5. nodejs 发起http请求

    http://nodejs.cn/api/http.html#http_http_request_options_callback http://yijiebuyi.com/blog/8221eb14 ...

  6. nodejs处理get请求

    主要记录下获取get请求里面的参数的问题. 假设有这样一个链接 urlString='hello?name=LiLei&position=general' 要从这个链接里提取出参数name和p ...

  7. nodejs笔记2——请求路由

    对于不同的URL请求,服务器应该有不同的反应.我们要为路由提供请求的URL和其他需要的GET及POST参数,随后路由需要根据这些数据来执行相应的代码.我们需要的所有数据都会包含在request对象中, ...

  8. nodejs中https请求失败,无报错

    今天群里一位同学在做练习的时候,采用https例子: // curl -k https://localhost:8000/ const https = require('https'); const ...

  9. nodejs获取post请求发送的formData数据

    前端post请求发送formData的类型数据时,需要服务端引入中间件body-parser,主要原因是post请求发送的数据,是在http的body里面,所以需要进行解析,否则获取不到数据(数据为空 ...

随机推荐

  1. 51nod 1163 贪心

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1163 1163 最高的奖励 基准时间限制:1 秒 空间限制:131072 ...

  2. derby_学习_00_资源帖

    一.精选资料 二.参考资料

  3. Microsoft Visual Studio Ultimate 2013 RC 离线安装程序

    Microsoft Visual Studio Ultimate 2013 RC 离线安装程序 ☆ 微软官网地址:☆ http://www.microsoft.com/en-us/download/d ...

  4. BEC listen and translation exercise 9

    You will do foolish things, but do them with enthusiasm. 你难免会做傻事,但要做,就做得满怀激情. In addition, there sho ...

  5. shell split函数的使用

    #!/bin/awk -f BEGIN{FS=","} {split($1,name," "); for (i in name) print name[i] }

  6. Unity3D for Android 纹理压缩支持

    http://blog.csdn.net/asd237241291/article/details/48548557 首先附图:Unity3D for Android支持的纹理压缩格式 纹理压缩可以通 ...

  7. 学习动态性能表(14)--v$parameter&v$system_parameter

    学习动态性能表 第14篇--V$PARAMETER&V$SYSTEM_PARAMETER  2007.6.11 这两个视图列出的各参数项名称以及参数值.V$PARAMETER显示执行查询的se ...

  8. python if语句,while语句

    一,if语句: python中最常用的判断语句,基本格式: 1.if else格式 if  条件: 结果 else: 结果 """ if 条件: 满足条件执行代码 els ...

  9. poj 3421 X-factor Chains——质因数分解

    题目:http://poj.org/problem?id=3421 记忆化搜索竟然水过去了.仔细一想时间可能有点不对,但还是水过去了. #include<iostream> #includ ...

  10. 3、Selenium调用IEDriverServer打开IE浏览器

    学习Selenium时若想调用IE浏览器,均需要以下步骤 (1).http://selenium-release.storage.googleapis.com/index.html 下载IEDrive ...