node.js GET与POST请求

标签 get post node.js 栏目 Node.js
原文   http://blog.csdn.net/chy555chy/article/details/52523165
 
var http = require('http');
var url = require('url'); createServer();
submitByGet();
submitByPost(); function createServer() {
http.createServer(function(req, res){
if(req.method.toUpperCase() == 'GET') {
res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
res.write('submit by ' + req.method.toUpperCase() + '\n');
//url.parse后得到的是一个json对象
res.write(JSON.stringify(url.parse(req.url))+'\n');
//虽然说url.parse后是一个json对象,但是用点号('.')取得它的值以后就是一个字符串对象了
res.end(url.parse(req.url).query+'\n');
} else if (req.method.toUpperCase() == 'POST') {
res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
var postData = 'submit by ' + req.method.toUpperCase() + '\n';
//因为post方式的数据不太一样可能很庞大复杂,所以要添加监听来获取传递的数据
req.addListener('data', function(data) {
postData += data;
}).addListener('end', function(data) {
res.write(postData+'\n');
//url.parse后得到的是一个json对象
res.end(JSON.stringify(url.parse(req.url))+'\n');
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain;charset=utf-8'});
res.end("{'errcode':404,'errmsg':'404 网页未找到'}\n");
}
}).listen(8080, function(){
console.log('listen on port 8080...');
});
} //因为绝大数网络请求都是get请求,所以官方单独对get请求做了个简化版
function submitByGet() {
var urlPath = 'http://127.0.0.1:8080/index.html?' + encodeURIComponent('name=龙神&password=123456');
http.get(urlPath, function(response){
response.setEncoding('utf-8');
console.log('状态码 : ' + response.statusCode);
console.log('response.headers = ' + JSON.stringify(response.headers));
//注意:这里如果不赋空值的话,undefined会被转为string添加进去
var receivedData = '';
response.on('data', function(chunk) {
receivedData += chunk;
}).on('end', function() {
//默认获取的数据是经过encodeURL之后的数据,需要使用decode解码
console.log('receivedRawData : ' + receivedData);
console.log('receivedDecodeData : ' + decodeURIComponent(receivedData));
});
}).on('error', function(e){
console.error(e.message);
});
} function submitByPost() {
//以键值对的形式构造的变量默认情况下都是一个对象
var sendData = {'name':'chy龙神', 'password':'123456'};
var postData = encodeURIComponent(JSON.stringify(sendData));
//只有post时,才需要Content-Length
var req = http.request({port:'8080', path:'http://localhost:8080/index.html', method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, 'Content-Length': postData.length}, function(response){
response.setEncoding('UTF8');
console.log('状态码 : ' + response.statusCode);
console.log('response.headers = ' + JSON.stringify(response.headers));
//注意:这里如果不赋空值的话,undefined会被转为string添加进去
var receivedData = '';
response.on('data', function(chunk) {
receivedData += chunk;
}).on('end', function(){
//默认获取的数据是经过encodeURL之后的数据,需要使用decode解码
console.log('receivedRawData : ' + receivedData);
console.log('receivedDecodeData : ' + decodeURIComponent(receivedData));
});
}).on('error', function(e){
console.error(e.message); });
//write仅对post方法有效
req.write(postData);
//end方法可以和request方法连写,但是write不可以
req.end();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>get-post-demo</title>
</head>
<body>
<form method="get" action="http://127.0.0.1:8080" >
<input name="name" type="text" value="freddon" />
<input name="password" type="password" value="123456"/>
<input type="submit" value="submit by GET" />
</form>
<form method="post" action="http://127.0.0.1:8080" >
<input name="name" type="text" value="freddon" />
<input name="password" type="password" value="123456"/>
<input type="submit" value="submit by POST" />
</form>
</body>
</html>

node.js GET与POST请求的更多相关文章

  1. Node.js:GET/POST请求

    ylbtech-Node.js:GET/POST请求 1.返回顶部 1. Node.js GET/POST请求 在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交. 表单提交到服务器一般 ...

  2. Node.js模拟发起http请求从异步转同步的5种方法

    使用Node.js模拟发起http请求很常用的,但是由于Node模块(原生和第三方库)提供里面的方法都是异步,对于很多场景下应用很麻烦,不如同步来的方便.下面总结了几个常见的库API从异步转同步的几种 ...

  3. Node.js 使用 soap 模块请求 WebService 服务接口

    项目开发中需要请求webservice服务,前端主要使用node.js 作为运行环境,因此可以使用soap进行请求. 使用SOAP请求webservice服务的流程如下: 1.进入项目目录,安装 so ...

  4. node.js 针对不同的请求路径(url) 做出不同的响应

    边看这个边写的: http://wenku.baidu.com/link?url=C4yLe-TVH6060u_x4t34H3Ze8tjoL7HjJaKgH-TvHnEYl-T_gAMYwhmrCeM ...

  5. Node.js~ioredis处理耗时请求时连接数瀑增

    回到目录 关于redis连接数过高的解释 对于node.js开发环境里,使用传统的redis或者使用ioredis都是不错的选择,而在处理大数据请求程中,偶尔出现了连接池( redis服务端的最大可用 ...

  6. 【node.js】GET/POST请求、Web 模块

    获取GET请求内容 node.js 中 url 模块中的 parse 函数提供了这个功能. var http = require('http'); var url = require('url'); ...

  7. node.js如何让前端请求时能跨域

    1995年,Netscape提出了一个著名的安全策略.现在所有支持JavaScript 的浏览器都会使用这个策略.所谓同源是指,域名,协议,端口相同. 当一个浏览器的两个tab页中分别打开来 百度和谷 ...

  8. Node.js:get/post请求、全局对象、工具模块

    一.GET/POST请求 在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交.表单提交到服务器一般都使用 GET/POST 请求. 1.获取GET请求内容 由于GET请求直接被嵌入在路径 ...

  9. vue-cli3.0+node.js+axios跨域请求session不一样的问题

    一.问题重述 使用的是,前后端分离,前端vue+axios请求,后端使用node搭建服务端接口,遇到的问题是,我通过登录接口吧数据存储型在session,我登录上以后,发现再次验证登录(另一个接口)的 ...

随机推荐

  1. Office--CVE-2017-11882【远程代码执行】

    Office远程代码执行漏洞现POC样本 最近这段时间CVE-2017-11882挺火的.关于这个漏洞可以看看这里:https://www.77169.com/html/186186.html 今天在 ...

  2. Docker 版ansible galera集群

    1. 部署galera集群 利用四台主机cicd.node1.node2.node3来搭建galera集群. 1> 上传压缩包至cicd,解压得到ansible配置文件 [root@cicd ~ ...

  3. flask通过nginx代理后base_url拿不到正确的url_scheme2016-04-14 12:31

    http://www.axiaoxin.com/article/210/ Nginx配置了https请求后,用户发起https请求时首先和Nginx建立连接,完成SSL握手,而后Nginx作为代理是以 ...

  4. dfs 二叉树中序遍历迭代解法——求解BST中第k小元素

    BST中第K小的元素 中文English 给一棵二叉搜索树,写一个 KthSmallest 函数来找到其中第 K 小的元素. Example 样例 1: 输入:{1,#,2},2 输出:2 解释: 1 ...

  5. Graylog-centos安装

    graylog安装 1.先决条件 yum install java-1.8.0-openjdk-headless.x86_64 -y #安装java软件包 yum install epel-relea ...

  6. php怎么识别真实ip

    PHP 里用来获取客户端 IP 的变量有这些: $_SERVER['HTTP_CLIENT_IP'] 这个头是有的,但是很少,不一定服务器都实现了.客户端可以伪造.(推荐学习:PHP编程从入门到精通) ...

  7. ES6 的class类 笔记

    class Person{ // 构造 constructor(x,y){ this.x = x; this.y = y; } toString(){ return (this.x + "的 ...

  8. (尚029)Vue_案例_交互footer组件功能

    需要实现界面截图: 难点分析:sAllCheck必须定义为计算属性 1.想到问题: 一旦写一个组件,需要接收哪些属性?? 因为只有属性确定了,标签才好写 todos属性可以确定三个方面的显示 2.做交 ...

  9. tab吸顶的神奇-- css粘性属性

    position: -webkit-sticky; position: sticky; top: 0.86rem; //可以自定义设置大小 亲测,目前谷歌浏览器等都已经支持该属性.

  10. ESA2GJK1DH1K微信小程序篇: 测试微信小程序扫描Air202上面的二维码绑定设备,并通过MQTT控制设备

    前言 一,微信小程序篇小程序下载(该功能为小程序篇基础功能源码) 实现功能概要 微信小程序通过扫描GPRS上的二维码,绑定GPRS设备.然后使用小程序通过GPRS远程控制开发板上的继电器, 远程显示单 ...