创建新的服务器


创建一个简单的服务

var http = require("http");

var server = http.createServer();
server.listen(8888);

这段代码只会启动一个侦听8888端口的服务器,不会应答,不会任何事,所以是无意义的。

下面创建一个有意义的服务器

var http = require("http");

http.createServer(function(request, response) {
console.log('get request');
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);

结果:

//服务端
$ node http.js
get request
//客户端
$ curl localhost:8888
Hello World

这里我们通过response.writeHead发送一个请求状态码和内容类型,使用 response.write() 函数在HTTP响应主体中发送文本“Hello World"。

response.end()这个方法告诉服务器,所有的响应头和响应体已经发送,服务器可以认为消息结束。

在curl下测试不出我们请求两次的问题,我们在浏览器端输入:http://localhost:8888/

Request Pathname  Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/',
path: '/',
href: '/' }
Request Pathname Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/favicon.ico',
path: '/favicon.ico',
href: '/favicon.ico' }

发现请求了两次。

注意:当我们在服务器访问网页时,我们的服务器可能会输出两次“get request”。那是因为大部分浏览器都会在你访问 http://localhost:8888/ 时尝试读取 http://localhost:8888/favicon.ico )

解析请求路径


这时候我们需要另外一个模块,url

var http = require("http");
var url = require("url") http.createServer(function(request, response) {
var pathname = url.parse(request.url).pathname;
console.log('Request Pathname ',pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);

发送请求:localhost:8888/demo/test

curl localhost:8888/demo/test

查看解析的url结果:

Request Pathname  /demo/test

我们取到浏览请求的url,这个可以帮助我们做路由映射。

url.parse很神奇,那我们再来多了解一点。

将原来的代码处url.parse修改一下

pathname = url.parse(request.url)

发送请求:http://localhost:8888/select?page=10&blog=nodejs

  Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?page=10&blog=nodejs',
query: 'page=10&blog=nodejs',
pathname: '/select',
path: '/select?page=10&blog=nodejs',
href: '/select?page=10&blog=nodejs' }

这就是整个解析后的url。

解析请求参数


使用querystringnodejs自带的模块解析参数

修改一下代码:

var http = require("http");
var url = require("url");
var querystring = require('querystring') http.createServer(function(request, response) {
var pathname = url.parse(request.url);
var query = querystring.parse(pathname.query);
console.log('query ',query);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
query  { page: '10', blog: 'nodejs' }

querystring.parse()有点类似于JSON.parse()

querystring.stringify()有点类似于JSON.stringify()

查看有querystring 哪些方法:

> var querystring = require('querystring')
undefined
> querystring
{ unescapeBuffer: [Function],
unescape: [Function],
escape: [Function],
encode: [Function],
stringify: [Function],
decode: [Function],
parse: [Function] }

发送post请求


这个例子有点复杂。

我们先创建一个服务器localhost:8000,然后通过自定义路由来处理请求。这里我们还是用http.request()发送了一个到localhost:8000/test的请求,并尝试获取post的数据。

var http = require("http");
var url = require("url");
var querystring = require('querystring') http.createServer(function(request, response) {
var pathname = url.parse(request.url);
var query = querystring.parse(pathname.query); if (pathname.pathname === '/getDo') { //处理localhost:8000/getDo
response.writeHead(200, { "Content-Type": "text/plain" });
response.write("Hello World");
response.end();
} else if (pathname.pathname === '/postDo') { //处理localhost:8000/postDo
postTest(response);
} else if (pathname.pathname === '/test') {
var jsonData = '';
request.on("data", function(data) {
jsonData += data
console.log('接受数据中。。。');
});
request.on("end", function() {
console.log('接受完成!');
console.log(querystring.parse(jsonData));
})
} }).listen(8888); function postTest(response) {
var postData = querystring.stringify({
'msg': 'Hello World!'
})
//发送post请求localhost:8000/test并带上参数postData
var options = {
hostname: 'localhost',
port: 8888,
path: '/test',
method: 'POST',
headers: {
'Content-Type': '"text/plain',
'Content-Length': postData.length
}
}; var req = http.request(options); req.write(postData);
req.end()
}
接受数据中。。。
接受完成!
{ msg: 'Hello World!' }

这里我们通过请求localhost:8000/postDo的时候,又通过http发送了localhost:8000/test这个请求,并通过req.write(postData)带上了post的参数。

应该这里没有使用任何框架,post的数据必须通过

var jsonData = '';
request.on("data", function(data) {
jsonData += data
console.log('接受数据中。。。');
});
request.on("end", function() {
console.log('接受完成!');
console.log(querystring.parse(jsonData));
})

这样的形式来拼接。

NodeJs之http的更多相关文章

  1. NodeJs之OS

    OS Node.js提供了一些基本的底层操作系统的模块OS. API var os = require('os'); console.log('[arch] 操作系统CPU架构'+os.arch()) ...

  2. NodeJs之Path

    Path模块 NodeJs提供的Path模块,使得我们可以对文件路径进行简单的操作. API var path = require('path'); var path_str = '\\Users\\ ...

  3. NodeJs之调试

    关于调试 当我们只专注于前端的时候,我们习惯性F12,这会给我们带来安全与舒心的感觉. 但是当我们使用NodeJs来开发后台的时候,我想噩梦来了. 但是也别泰国担心,NodeJs的调试是很不方便!这是 ...

  4. NodeJs在Linux下使用的各种问题

    环境:ubuntu16.04 ubuntu中安装NodeJs 通过apt-get命令安装后发现只能使用nodejs,而没有node命令 如果想避免这种情况请看下面连接的这种安装方式: 拓展见:Linu ...

  5. NodeJs之child_process

    一.child_process child_process是NodeJs的重要模块.帮助我们创建多进程任务,更好的利用了计算机的多核性能. 当然也支持线程间的通信. 二.child_process的几 ...

  6. nodejs进阶(6)—连接MySQL数据库

    1. 建库连库 连接MySQL数据库需要安装支持 npm install mysql 我们需要提前安装按mysql sever端 建一个数据库mydb1 mysql> CREATE DATABA ...

  7. 图片访问实时处理的实现(nodejs和php)

    我在访问时光网.网易云音乐等网站时,发现将它们页面中的一些图片URL修改一下就可以得到不同尺寸的图片,于是思考了其实现方案,我的思路是:URL Rewrite + 实时处理 + 缓存,对用户请求的UR ...

  8. nodejs进阶(4)—读取图片到页面

    我们先实现从指定路径读取图片然后输出到页面的功能. 先准备一张图片imgs/dog.jpg. file.js里面继续添加readImg方法,在这里注意读写的时候都需要声明'binary'.(file. ...

  9. nodejs进阶(3)—路由处理

    1. url.parse(url)解析 该方法将一个URL字符串转换成对象并返回. url.parse(urlStr, [parseQueryString], [slashesDenoteHost]) ...

  10. 【原】nodejs全局安装和本地安装的区别

    来微信支付有2年多了,从2年前的互联网模式转变为O2O模式,主要的场景是跟线下的商户去打交道,不像以往的互联网模式,有产品经理提需求,我们帮忙去解决问题. 转型后是这样的,团队成员更多需要去寻找业务的 ...

随机推荐

  1. ES6-01:常量与变量的声明

    首先,我们声明一个变量: //定义一个变量num,并赋值为10: let num = 10; //进行打印 console.log(num); let与var有所不同: 语法特点1:let变量只能在当 ...

  2. DAX/PowerBI系列 - 写在前面

    今天讲的主角是: 不过,先上一个图--2017 Gartner商业智能和数据分析魔力象限 DAX关注这个玩意儿有好一段时间了,刚开始的时候(2014年?)是从Excel里面认识的.2014年当时公司用 ...

  3. Tinywebserver:一个简易的web服务器

    这是学习网络编程后写的一个练手的小程序,可以帮助复习I/O模型,epoll使用,线程池,HTTP协议等内容. 程序代码是基于<Linux高性能服务器编程>一书编写的. 首先回顾程序中的核心 ...

  4. Android性能测试工具Emmagee

    下面介绍一个简单实用的Android性能软件 ~~欢迎加入测试群574875837一起讨论研究 一.Emmagee 简介 Emmagee主要用于监控单个App的CPU,内存,流量,启动耗时,电量,电流 ...

  5. ROJ 1166 超级贞鱼

    1166: 超级贞鱼 Time Limit: 1 Sec  Memory Limit: 128 MB [Submit][Status] 传送门 Description 马达加斯加贞鱼是一种神奇的双脚贞 ...

  6. 基于Asp.Net Core Mvc和EntityFramework Core 的实战入门教程系列-1

    来个目录吧: 第一章 第二章 第三章 暂时就这么多.后面路线更新吧 本系列文章为翻译加上我个人的使用心得理解,希望帮助热爱学习的程序员. 珍重声明:本系列文章会跟原文有点出入,去掉了罗里吧嗦的文字. ...

  7. 算法模板——线段树6(二维线段树:区域加法+区域求和)(求助phile)

    实现功能——对于一个N×M的方格,1:输入一个区域,将此区域全部值作加法:2:输入一个区域,求此区域全部值的和 其实和一维线段树同理,只是不知道为什么速度比想象的慢那么多,求解释...@acphile ...

  8. JDBC整合c3p0数据库连接池 解决Too many connections错误

    前段时间,接手一个项目使用的是原始的jdbc作为数据库的访问,发布到服务器上在运行了一段时间之后总是会出现无法访问的情况,登录到服务器,查看tomcat日志发现总是报如下的错误. Caused by: ...

  9. iOS项目之同时点击多个按钮解决方案

    自己的项目完成后,在测试中出现了一个情况,同时点击界面中的多个按钮,会跳转多个界面.然后又看了看别的app,发现也有这样的情况, 如图 上面是我手机上美团app的截图,上面的分类同时选择多个时,只能跳 ...

  10. reactjs Uncaught TypeError: Cannot read property 'location' of undefined

    reactjs Uncaught TypeError: Cannot read property 'location' of undefined reactjs 路由配置 怎么跳转 不成功 国内搜索引 ...