node.js在windows下的学习笔记(5)---用NODE.JS创建服务器和客户端
2014-09-15 02:20
776 查看
//引入http模块 var http = require('http'); //调用http的createServer的方法,这个方法有一个回调函数,这个回调数 //的作用是当有请求发送给服务器的时候,就执行这个回调函数 http.createServer(function (req, res) { //发送 res.end('Hello World\n'); }).listen(3000, "127.0.0.1");//端口和IP的绑定 console.log('Server running at ' target='_blank'>http://127.0.0.1:3000/');[/code]
以上代码,创建了一个服务器,并设置了发送给客户端的内容,下面讲一下Node.js中的重定向var http = require('http'); http.createServer(function (req, res) { //重定向,writeHead方法 res.writeHead(301, { 'Location': 'http://www.baidu.com' }); res.end(); }).listen(3000, "127.0.0.1"); console.log('Server running at ' target='_blank'>http://127.0.0.1:3000/');[/code]
通过设置路由,来响应不同的请求(本质),这里,其实会越来越复杂的,因为如果有很多种类的响应的话,if--else会越来越多,后面会介绍一下Express框架var http = require('http'), url = require('url'); http.createServer(function (req, res) { //解析URL,取得路径名 var pathname = url.parse(req.url).pathname; if (pathname === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Home Page\n') } else if (pathname === '/about') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('About Us\n') } else if (pathname === '/redirect') { res.writeHead(301, { 'Location': '/' }); res.end(); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Page not found\n') } }).listen(3000, "127.0.0.1"); console.log('Server running at ' target='_blank'>http://127.0.0.1:3000/');[/code]
用Node.js创建一个客户端var http = require('http'); var options = { host: 'shapeshed.com', port: 80, path: '/' }; http.get(options, function(res) { if (res.statusCode == 200) { console.log("The site is up!"); } else { console.log("The site is down!"); } }).on('error', function(e) { console.log("There was an error: " + e.message); });
相关文章推荐
- node.js学习笔记之创建UDP服务器与客户端
- node.js 学习笔记一:创建一个服务器
- Node.js学习笔记(4)——除了HTTP(服务器和客户端)部分
- node.js学习笔记(3)_极客学院_服务器入门
- node.js在windows下的学习笔记(10)---URL模块
- NodeJS-学习笔记(1)--windows7下node.js环境的搭建
- Node.js入门学习笔记-IDE选择/配置之WebStorm(windows)
- 客户端网络pomelo学习笔记 (3) node.js 与 c 客户端 Diffie-Hellman 密钥交换算法的实现客户端网络
- Node.js权威指南 (8) - 创建HTTP与HTTPS服务器及客户端
- Node.js 学习笔记--- (2)创建一个简单的博客工程
- node.js在windows下的学习笔记(4)---同步,异步,回调的概念
- node.js在windows下的学习笔记(8)---进程管理Process
- Node.js学习笔记1:windows环境搭建
- Node.js入门学习笔记-IDE选择/配置之WebStorm(windows)
- node.js在windows下的学习笔记(3)---npm
- node.js在windows下的学习笔记(9)---文件I/O模块
- Node.js学习笔记【1】入门(服务器JS、函数式编程、阻塞与非阻塞、回调、事件、内部和外部模块)
- node.js在windows下的学习笔记(1)---安装node.js
- node.js在windows下的学习笔记(2)---简单熟悉一些命令
- Node.js入门学习笔记-IDE选择/配置之WebStorm(windows)