//引入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 http://127.0.0.1:3000/‘);
以上代码,创建了一个服务器,并设置了发送给客户端的内容,下面讲一下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 http://127.0.0.1:3000/‘);
通过设置路由,来响应不同的请求(本质),这里,其实会越来越复杂的,因为如果有很多种类的响应的话,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 http://127.0.0.1:3000/‘);
用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); });