node.js GET与POST请求
node.js GET与POST请求
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请求的更多相关文章
- Node.js:GET/POST请求
ylbtech-Node.js:GET/POST请求 1.返回顶部 1. Node.js GET/POST请求 在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交. 表单提交到服务器一般 ...
- Node.js模拟发起http请求从异步转同步的5种方法
使用Node.js模拟发起http请求很常用的,但是由于Node模块(原生和第三方库)提供里面的方法都是异步,对于很多场景下应用很麻烦,不如同步来的方便.下面总结了几个常见的库API从异步转同步的几种 ...
- Node.js 使用 soap 模块请求 WebService 服务接口
项目开发中需要请求webservice服务,前端主要使用node.js 作为运行环境,因此可以使用soap进行请求. 使用SOAP请求webservice服务的流程如下: 1.进入项目目录,安装 so ...
- node.js 针对不同的请求路径(url) 做出不同的响应
边看这个边写的: http://wenku.baidu.com/link?url=C4yLe-TVH6060u_x4t34H3Ze8tjoL7HjJaKgH-TvHnEYl-T_gAMYwhmrCeM ...
- Node.js~ioredis处理耗时请求时连接数瀑增
回到目录 关于redis连接数过高的解释 对于node.js开发环境里,使用传统的redis或者使用ioredis都是不错的选择,而在处理大数据请求程中,偶尔出现了连接池( redis服务端的最大可用 ...
- 【node.js】GET/POST请求、Web 模块
获取GET请求内容 node.js 中 url 模块中的 parse 函数提供了这个功能. var http = require('http'); var url = require('url'); ...
- node.js如何让前端请求时能跨域
1995年,Netscape提出了一个著名的安全策略.现在所有支持JavaScript 的浏览器都会使用这个策略.所谓同源是指,域名,协议,端口相同. 当一个浏览器的两个tab页中分别打开来 百度和谷 ...
- Node.js:get/post请求、全局对象、工具模块
一.GET/POST请求 在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交.表单提交到服务器一般都使用 GET/POST 请求. 1.获取GET请求内容 由于GET请求直接被嵌入在路径 ...
- vue-cli3.0+node.js+axios跨域请求session不一样的问题
一.问题重述 使用的是,前后端分离,前端vue+axios请求,后端使用node搭建服务端接口,遇到的问题是,我通过登录接口吧数据存储型在session,我登录上以后,发现再次验证登录(另一个接口)的 ...
随机推荐
- 假设检验、T检验
假设检验初步: https://cosx.org/2010/11/hypotheses-testing t检验:https://mangowu97.github.io/%E5%82%BB%E7%93% ...
- SpringCloud2.0 Eureka Server 服务中心 基础教程(二)
1.创建[服务中心],即 Eureka Server 1.1.新建 Spring Boot 工程,工程名称: springcloud-eureka-server 1.2.工程 pom.xml 文件添加 ...
- SQL基础篇(MICK)
SQL基础教程(Mick) 数据库和SQL C:\PostgreSQL\9.5\bin\psql.exe -U postgres -d shop 数据库的基本概念 数据库(DB):将大量数据保存起来, ...
- CentOS7.5搭建Rsync,实现文件同步
Rsync(remote sync)是UNIX及类UNIX平台下一款神奇的数据镜像备份软件,它不像FTP或其他文件传输服务那样需要进行全备份,Rsync可以根据数据的变化进行差异备份,从而减少数据流量 ...
- discuz x3.3排行首页图片显示更多的图片
找到\source\include\misc\misc_ranklist_index.php文件,修改41行 $ranklist = getranklist_pictures_index(9); 为 ...
- 学习:费马小定理 & 欧拉定理
费马小定理 描述 若\(p\)为素数,\(a\in Z\),则有\(a^p\equiv a\pmod p\).如果\(p\nmid a\),则有\(a^{p-1}\equiv 1\pmod p\). ...
- 软件测试之Monkey 初步了解(入门级II)
1. 先熟悉monkey基本命令: cls 清除 首先测试设备是否连接成功,在命令行中输入:adb devices 查看adb版本: adb version 查看虚拟机版本:nox_adb ver ...
- 使用tensorflow时,关于GPU的设置
查看显卡使用情况: nvidia-smi 设置tensorflow按需分配资源: import os os.environ["CUDA_DEVICE_ORDER"] = " ...
- python --装饰器内容讲解
python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能. 3.1 定义装饰器 ...
- OpenCV 学习笔记(2) 使用鼠标绘制矩形并截取和保存矩形区域图像
http://www.cnblogs.com/lidabo/p/3437587.html 0 效果展示 1工程源码 #include <opencv2/core/core.hpp> # ...