NodeJS Web模块
NodeJS Web模块
本文介绍nodeJS的http模块的基本用法,实现简单服务器和客户端
经典Web架构
- Client:客户端一般指浏览器,通过HTTP协议向服务器发送请求(request)
- Server:服务器,接受客户端请求,并向服务器发送响应数据(response),主流的有Apache、Nginx、IIS
- Business:业务逻辑层,核心应用逻辑所在,与数据库、文件系统、外部程序交互
- Data:数据层,主要由数据库组成
Node服务器
server.js
var http = require('http')
var fs = require('fs')
var url = require('url')
// 创建服务器
http.createServer(function (request, response) {
// 解析请求,包括文件名
var pathname = url.parse(request.url).pathname
// 日志输出请求的文件名
console.log("Request for "+pathname+" received.")
// 从文件系统中读取请求的内容
fs.readFile(pathname.substr(1),function (err, data) {
if (err){
console.error(err)
//返回错误信息404
response.writeHead(404,{"Content-Type":"text/html"})
}
else{
// 请求成功
response.writeHead(200,{"Content-Type":"text/html"})
response.write(data.toString())
}
response.end()
})
}).listen(8000) //在8000端口监听
console.log("Server is running at http://127.0.0.1:8000")
在同一目录下新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
运行server.js之后,在浏览器中访问http://127.0.0.1:8000/index.html,就会返回helloworld的页面
Node客户端
client.js
var http = require('http')
// 配置参数
var options = {
host:'localhost',
port:'8000',
path:'/index.html'
}
// 向服务器发送请求
var req = http.request(options, function (response) {
var body = ''
// 接受数据块
response.on('data',function (data) {
body += data
})
response.on('end',function () {
console.log(body)
})
})
req.end()
服务器在运行的同时,再开一个终端
$ node client.js
输出为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
GET请求
var http = require('http')
var url = require('url')
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain charset=utf-8'})
// 解析url参数
var params = url.parse(req.url,true).query
res.write('网站名: '+params.name)
res.write('\n')
res.write('网站url: '+ params.url)
res.end()
}).listen(8000)
浏览器中访问http://localhost:8000/?name=百度&url=www.baidu.com
得到响应
POST请求
node没有设置专门对post的请求,一直等待用户输入开销比较大,而是采用了监听用户向服务器发送数据写入的方式实现
var http = require('http')
var fs = require('fs')
var querystring = require('querystring')
var postHTML
fs.readFile('index.html',function (err,data) {
if (err){
console.error(err)
}
else{
postHTML = data
}
})
http.createServer(function (req, res) {
var data = ""
req.on('data', function (chunk) {
data += chunk
})
// 数据读完之后解析
req.on('end',function () {
// 解析参数
console.log(data)
data = querystring.parse(data)
// 写响应头
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'})
if (data['name'] && data['url']){
res.write("网站名"+ data['name'])
res.write("<br>")
res.write("网站url"+ data['url'])
}
else{
res.write(postHTML)
}
res.end()
})
}).listen(8000)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Page</title>
</head>
<body>
<form method="post">
网站名:<input name="name"><br>
网站url:<input name="url"><br>
<input type="submit">
</form>
</body>
</html>
访问localhost:8000后输入表单内容并提交,服务器会给出相应
NodeJS Web模块的更多相关文章
- Nodejs Web模块( readFile 根据请求跳转到响应html )
index.js 根据请求的路径pathname,返回响应的页面. var http = require('http'); var fs = require('fs'); var url = requ ...
- Nodejs学习笔记(3) 创建服务器:Web 模块(http)与 express 框架
目录 参考资料 1. 使用 http 模块创建服务器 1.1 实现思路及代码 1.2 HTTP 结构 1.2.1 Request中的重要字段 1.2.2 Response 头信息:文件类型.状态码.连 ...
- NodeJS 常用模块
NodeJS 模块: n:NodeJS 版本管理/切换 参考: https://github.com/tj/n ExpressJS:Web 框架 参考: http://expressjs.com/ m ...
- Node.js Web模块
什么是Web服务器? Web服务器是处理由HTTP客户端发送的,如web浏览器的HTTP请求的软件应用程序,并返回响应于客户端网页. Web服务器通常伴随着图片,样式表和脚本的HTML文档. 大多数W ...
- NodeJS常用模块介绍
收集了NodeJS开发中常用的一些模块. MVC框架 - Express Express 是轻量灵活的Nodejs Web应用框架,它可以快速地搭建网站.Express框架建立在Nodejs内置的Ht ...
- Nodejs WEB开发常用库和框架
我在Nodejs的体系里也算泡了很久了,的确非常喜欢javascript和Nodejs. 在我看来,用nodejs做web开发有以下几个优点: Javascript作为一个语法异常简单的脚本语言,约束 ...
- Node.js:Web 模块
ylbtech-Node.js:Web 模块 1.返回顶部 1. Node.js Web 模块 什么是 Web 服务器? Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服 ...
- nodejs事件模块
nodejs 事件模块 events 只有一个对象 EventEmitter . var EventEmitter = require('events').EventEmitter;var life ...
- 配置 Windows 下的 nodejs C++ 模块编译环境
根据 node-gyp 指示的 Windows 编译环境说明, 简单一句话就是 "Python + VC++ 编译环境". 所有需要的安装文件, 我都下载好放到百度云盘了: nod ...
随机推荐
- Android Https双向认证 + GRPC
keywords:android https 双向认证android GRPC https 双向认证 ManagedChannel channel = OkHttpChannelBuilder.for ...
- jquery轻量级数字动画插件jquery.countup.js
插件描述: jquery.countup.js 是一款轻量级jquery数字动画插件.该数字动画插件可以在页面滚动时,将指定的数字从0开始计数增加动画. 插件说明 jquery.countup.js ...
- twitter typeahead控件使用经历
typeahead控件可以用于自动完成这个功能,在jQuery的UI中也有自动完成的控件.以前都是用jQuery UI中的自动完成的控件,但这次想用个轻量级的自动完成的控件,因此就调查了一下typeh ...
- python全栈开发day85-查:数据表 数据头 增加列 展示多对多字段 反向解析编辑和删除按钮的url
直接上代码: # spark/service/sites.py from django.conf.urls import url from django.shortcuts import HttpRe ...
- 无法删除另一个分区的windows文件夹
转自:http://zhidao.baidu.com/link?url=77mJiLzVTdr9LzW4R6UYHZ8OJovvXsH8HQb0hyUKL4RKv2J3bItFJgJx-xqAEGOj ...
- angularjs 中通过 $location 进行路由跳转传参
$location.path('/page1').search({id: $scope.id,name:$scope.name}); 带参数跳转页面,在新的页面通过$routeParams接收参数 $ ...
- nginx+uwsgi启动Django项目
1.安装项目环境 系统环境:ubuntu16.04 python环境:python3.5.2 Django版本:django1.11.7 nginx环境:nginx_1.10.3 虚拟环境:virtu ...
- Shiro笔记(二)Shiro集成SpringMVC的环境配置
0.pom文件引入 <!-- SECURITY begin --> <dependency> <groupId>org.apache.shiro</group ...
- 无法启动 Maya 集成的 qt designer 的解决方法和原因 以及 中英文切换
无法启动 Maya 集成的 qt designer 的解决方法和原因 以及 中英文切换 前言: Maya 集成了 PySide,同时集成了qt designer,在 Maya 的安装目录下的 bin ...
- NP:建立可视化输入的二次函数数据点集np.linspace+np.random.shuffle+np.random.normal
import numpy as np import matplotlib.pyplot as plt def fix_seed(seed=1): #重复观看一样东西 # reproducible np ...