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,我登录上以后,发现再次验证登录(另一个接口)的 ...
随机推荐
- Linux chage命令详解
原文 chage命令用于密码实效管理,该是用来修改帐号和密码的有效期限,接下来通过本文给大家介绍Linux chage命令相关知识,本文介绍的非常详细,具有参考借鉴价值,感兴趣的朋友一起学习吧 lin ...
- Dockerfile(从无到有创建镜像)
本文原始地址:https://sitoi.cn/posts/43818.html 结构 DockerFile分为四部分组成: 基础镜像信息 维护者信息 镜像操作指令 容器启动时执行指令 基础镜像信息 ...
- Educational Codeforces Round 68 E. Count The Rectangles
Educational Codeforces Round 68 E. Count The Rectangles 传送门 题意: 给出不超过\(n,n\leq 5000\)条直线,问共形成多少个矩形. ...
- jenkins中jmeter项目流程图
- Beta产品测试报告:那周余嘉熊掌将得队、为了交项目干杯队
测试对象: 那周余嘉熊掌将得队 一.截图 安装截图 运行截图 二.测试情况 1.第一次上手体验感觉如何?能否正常运行? 界面UI设计令人眼前一亮,客户端和管理员端皆可正常运行.组件动画流畅,响应流畅, ...
- python应用-一组数的最大值,最小值,平均数
def foo(n): c=[] for _ in range (n): var=randint(60,100) c.append(var) print(c) total=0 max = c[0] m ...
- python基础语法9 生成器,面向对象编程思想,三元表达式,列表生成式,生成器表达式(生成式),匿名函数,内置函数
生成器 1.什么是生成器? 生成的工具. 生成器是一个 "自定义" 的迭代器, 本质上是一个迭代器. 2.如何实现生成器 但凡在函数内部定义了的yield, 调用函数时,函数体代码 ...
- Mysql一些常见语句
Mysql一些常见语句 (1)展示所有的数据库名 SHOW DATABASES (2)选中某一个数据库 USE 数据库名字 (3)查看某一个表的结构 DESC 表名 (4)数据库的创建 CREATE ...
- Spring中AOP方式实现多数据源切换
作者:suroot spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性.而这样的方案就会不同于常见的单一数据实例的方案,这就要 ...
- vue cli4.0 配置环境变量
温馨提示:本文只适用于vue-cli 3.0 及以上的版本哦~ ------------------正文开始------------------ 开发项目时,经常会需要在不同环境中切换.那么我们如何配 ...