node与http模块
http模块实现简单的页面展示
const http=require('http')//注意:使用http模块需要先行引入
创建一个服务:
var server =http.createServer(function(req,res){
req=>resquest=>IncomingMessage类
res=>Response=>SeverResponse类
res.writeHead(200,{'ContentType':'text/html'})
ContentType由res返回文件扩展名决定
点击了解ContentType
写入html页面:
res.write(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{
height: 100px;
width: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="d1">啊</div>
<div class="d1">真</div>
<div class="d1">好</div>
<div class="d1">啊</div>
</body>
</html>`)
结束并监听
res.end()//不要在end后面再去修改你的请求
})
//http 默认80端口 https默认443端口
//域名可不填 计算机一般默认为 localhost 127.0.0.1
server.listen(3000)//server.listen(3000,域名)
http模块文本乱码处理
方法1:
const http = require('http')
var server = http.createServer(function(req,res){
res.writeHead(200,{"Content-type":"text/plain;charset=UTF-8"});//改变编译码(转中文)
res.write('你好啊!这是来自node的文本') //写身
res.end() //标志写完
})
server.listen(3000)
方法2:
const http = require('http')
var server = http.createServer(function(req,res){
res.setHeader("Content-Type","text/html;charset=UTF-8");//改变编译码(转中文)
res.end('你好啊!这是来自node的文本') //标志写完(未指定格式,此处乱码)
})
server.listen(3000)
http模块实现Html表单提交 a标签跳转 Ajax交互
Html页面代码(node5.html):
<!DOCTYPE html>
< html lang = " en" >
< head>
< meta charset = " UTF-8" >
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" >
< meta http-equiv = " X-UA-Compatible" content = " ie=edge" >
< title> Document</ title>
</ head>
< body>
< a href = " /txt?txtname=1" > 1111</ a>
< a href = " /txt?txtname=2" > 2222</ a>
< form action = " http://www.baidu.com/s" >
< input type = " text" name = " wd" >
< input type = " submit" value = " 提交" >
</ form>
< form action = " /txt" method = " GET" >
< input type = " text" name = " txtname" >
< input type = " submit" value = " 提交" >
</ form>
< form action = " /login" method = " POST" >
< input type = " text" name = " username" >
< input type = " password" name = " password" >
< input type = " submit" value = " 提交" >
</ form>
< script>
var xhr= new XMLHttpRequest ( )
xhr. open ( 'POST' , '/login' , true )
xhr. setRequestHeader ( 'Content-Type' , 'text/json' )
xhr. send ( JSON . stringify ( { username: '123' , password: '789654' } ) )
xhr. onreadystatechange = function ( ) {
if ( xhr. status== 200 && xhr. readyState== 4 ) {
console. log ( xhr. response)
}
}
</ script>
</ body>
</ html>
Node服务端代码:
const fs = require ( 'fs' )
const path = require ( 'path' )
const querystring = require ( 'querystring' )
const url = require ( 'url' )
const http = require ( 'http' )
var server = http. createServer ( function ( req, res) {
if ( req. method. toLowerCase ( ) == 'get' ) {
if ( req. url == '/' ) {
fs. readFile ( './node5.html' , { encoding: 'utf-8' } , function ( err, data) {
if ( err && err. code == 'ENOENT' ) {
res. writeHead ( 404 )
res. write ( '404 NOT FOUND' )
res. end ( )
}
res. writeHead ( 200 , { 'Content-Type' : 'text/html' } )
res. write ( data)
res. end ( )
} )
}
var urlParseObj = url. parse ( req. url)
var pathname_my = urlParseObj. pathname
var query_my = urlParseObj. query
var queryParseObj = querystring. parse ( query_my)
var txtname = queryParseObj. txtname
var lj = path. join ( './' , txtname '.txt' )
if ( pathname_my == '/txt' ) {
fs. readFile ( lj, { encoding: 'utf-8' } , function ( err, data) {
if ( err && err. code == 'ENOENT' ) {
res. writeHead ( 404 )
res. write ( '404 NOT FOUND' )
res. end ( )
}
res. setHeader ( "Content-Type" , "text/html;charset=UTF-8" ) ;
res. write ( data)
res. end ( )
} )
}
}
if ( req. method. toLowerCase ( ) == 'post' ) {
if ( req. url == '/login' ) {
var data = ''
req. on ( 'data' , function ( chunk) {
console. log ( chunk)
console. log ( chunk. toString ( ) )
data = chunk. toString ( )
} )
req. on ( 'end' , function ( ) {
console. log ( '请求完成' , data)
var resultObjName
console. log ( req. headers)
if ( req. headers[ 'content-type' ] == 'text/json' ) {
console. log ( '这是Ajax数据' data)
resultObjName = JSON . parse ( data) . username
console. log ( 'Ajax and JSON运行' )
}
else {
resultObjName = querystring. parse ( data) . username
}
console. log ( '已运行' resultObjName)
res. setHeader ( "Content-Type" , "text/html;charset=UTF-8" ) ;
res. write ( resultObjName)
res. end ( )
} )
}
}
} )
server. listen ( 3000 )
Http实现前台CSS JS JPG GIF引入
Html页面代码(index.html):
<!DOCTYPE html>
< html lang = " en" >
< head>
< meta charset = " UTF-8" >
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" >
< meta http-equiv = " X-UA-Compatible" content = " ie=edge" >
< title> Document</ title>
< link rel = " icon" href = " ./index.ico" >
< link rel = " stylesheet" href = " ./index.css" >
</ head>
< body>
< div class = " cheng" > 成功</ div>
< img src = " ./index.jpg" alt = " " >
< img src = " ./index.gif" alt = " " >
< script src = " ./index.js" > </ script>
</ body>
</ html>
Node服务端代码:
const http = require ( 'http' )
const fs= require ( 'fs' )
var server = http. createServer ( function ( req, res) {
if ( req. method. toLowerCase ( ) == "get" ) {
console. log ( req. method)
console. log ( req. url)
if ( req. url == '/' ) {
fs. readFile ( './index.html' , { encoding: 'utf-8' } , function ( err, data) {
res. writeHead ( 200 , { 'Content-Type' : 'text/html' } )
res. write ( data)
res. end ( )
} )
}
if ( req. url== '/index.css' ) {
fs. readFile ( './index.css' , { encoding: 'utf-8' } , function ( err, data) {
res. writeHead ( 200 , { 'Content-Type' : 'text/css' } )
res. write ( data)
res. end ( )
} )
}
if ( req. url== '/index.js' ) {
fs. readFile ( './index.js' , { encoding: 'utf-8' } , function ( err, data) {
res. writeHead ( 200 , { 'Content-Type' : 'application/x-javascript' } )
res. write ( data)
res. end ( )
} )
}
if ( req. url== '/index.jpg' ) {
fs. readFile ( './index.jpg' , function ( err, data) {
res. writeHead ( 200 , { 'Content-Type' : 'image/jpeg' } )
res. write ( data)
res. end ( )
} )
}
if ( req. url== '/index.gif' ) {
fs. readFile ( './index.gif' , function ( err, data) {
res. writeHead ( 200 , { 'Content-Type' : 'image/gif' } )
res. write ( data)
res. end ( )
} )
}
}
} )
server. listen ( 3000 )
Node服务端代码(升级):
const http = require ( 'http' )
const fs = require ( 'fs' )
const path = require ( 'path' )
const mime = require ( './mime' )
const static = './'
var sever = http. createServer ( function ( req, res) {
if ( req. method. toLowerCase ( ) == 'get' ) {
console. log ( req. url)
if ( req. url == '/' ) {
fs. readFile ( './index.html' , { encoding: 'utf-8' } , function ( err, data) {
res. writeHead ( 200 , { 'Content-Type' : 'text/html' } )
res. write ( data)
res. end ( )
} )
}
if ( req. url. indexOf ( '.' ) > - 1 ) {
var lj = path. join ( static , req. url)
console. log ( lj)
fs. readFile ( lj, function ( err, data) {
console. log ( '运行' )
res. writeHead ( 200 , { 'Content-Type' : mime. JudgeType ( req. url) } )
res. write ( data)
res. end ( )
} )
}
}
} )
sever. listen ( 3000 )
Node服务端代码(升级)mime文件:
const path= require ( 'path' )
var JudgeType = function ( filename) {
var ext= path. parse ( filename) . ext
switch ( ext) {
case '.html' :
return 'text/html'
case '.css' :
return 'text/css'
case '.js' :
return 'application/x-javascript'
case '.png' :
return 'image/png'
case '.jpg' :
return 'image/jpeg'
case '.gif' :
return 'image/gif'
case '.ico' :
return 'image/x-icon'
}
}
exports. JudgeType= JudgeType
Http解决跨域问题及范例
const http = require ( 'http' )
var server = http. createServer ( function ( req, res) {
if ( req. method. toLowerCase ( ) == 'get' ) {
console. log ( req. url)
if ( req. url == '/' ) {
res. setHeader ( 'Access-Control-Allow-Origin' , '*' )
res. writeHead ( 200 , { 'Content-Type' : 'text/html' } )
res. write ( '456' )
res. end ( )
}
}
} )
server. listen ( 3000 )
http模块用GET POST方法实现登录验证
Html首页代码(node6(login).htm):
<!DOCTYPE html>
< html lang = " en" >
< head>
< meta charset = " UTF-8" >
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" >
< meta http-equiv = " X-UA-Compatible" content = " ie=edge" >
< title> Document</ title>
</ head>
< body>
< form action = " /login" >
< input type = " text" name = " username" >
< input type = " password" name = " password" >
< button> 点我</ button> < span> 此方法进入网址会显示出数据(GET)</ span>
</ form>
< br>
< form action = " /login" method = " POST" >
< input type = " text" name = " username" >
< input type = " password" name = " password" >
< button> 点我</ button> < span> 此方法进入看不到输入数据(POST)</ span>
</ form>
</ body>
</ html>
Html登录成功页面代码(node6().htm):
<!DOCTYPE html>
< html lang = " en" >
< head>
< meta charset = " UTF-8" >
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" >
< meta http-equiv = " X-UA-Compatible" content = " ie=edge" >
< title> Document</ title>
</ head>
< body>
成功进入
</ body>
</ html>
Node服务端代码:
const http = require ( 'http' )
const fs = require ( 'fs' )
const url = require ( 'url' )
const querystring = require ( 'querystring' )
var server = http. createServer ( function ( req, res) {
if ( req. method. toLowerCase ( ) == 'get' ) {
if ( req. url == '/' ) {
fs. readFile ( './node6(login).htm' , { encoding: 'utf-8' } , function ( err, data) {
if ( err && err. code == 'ENOENT' ) {
res. writeHead ( 403 )
res. write ( '403 FORBIDDEN' )
res. end ( )
}
res. writeHead ( 200 , { 'Content-Type' : 'text/html' } )
res. write ( data)
res. end ( )
} )
}
console. log ( req. url)
var urlObj = url. parse ( req. url)
var pathname = urlObj. pathname
var queryObj = querystring. parse ( urlObj. query)
if ( pathname == '/login' ) {
if ( queryObj. username == '昵称' && queryObj. password == '密码' ) {
fs. readFile ( './node6().htm' , { encoding: 'utf-8' } , function ( err, data) {
if ( err && err. code == 'ENOENT' ) {
res. writeHead ( 404 )
res. write ( '404 NOT FOUND' )
res. end ( )
}
res. writeHead ( 200 , { 'Content-Type' : 'text/html' } )
res. write ( data)
res. end ( )
} )
}
else {
res. setHeader ( "Content-Type" , "text/html;charset=UTF-8" )
res. write ( '密码错误' )
res. end ( )
}
}
}
if ( req. method. toLowerCase ( ) == 'post' ) {
if ( req. url == '/login' ) {
var data = ''
req. on ( 'data' , function ( chunk) {
data = chunk. toString ( )
} )
req. on ( 'end' , function ( ) {
console. log ( data)
var queryObj = querystring. parse ( data)
if ( queryObj. username == '昵称' && queryObj. password == '密码' ) {
fs. readFile ( './node6().htm' , { encoding: 'utf-8' } , function ( err, data) {
if ( err && err. code == 'ENOENT' ) {
res. writeHead ( 404 )
res. write ( '404 NOT FOUND' )
res. end ( )
}
res. writeHead ( 200 , { 'Content-Type' : 'text/html' } )
res. write ( data)
res. end ( )
} )
}
else {
res. setHeader ( "Content-Type" , "text/html;charset=UTF-8" )
res. write ( '密码错误' )
res. end ( )
}
} )
}
}
} )
server. listen ( 3000 )
Http模块中的Cookie
const http= require ( 'http' )
const fs = require ( 'fs' )
const querystring= require ( 'querystring' )
var server= http. createServer ( function ( req, res) {
if ( req. method. toLowerCase ( ) == 'get' ) {
if ( req. url== '/' ) {
fs. readFile ( './node6(login).htm' , { encoding: 'utf-8' } , function ( err, data) {
if ( err&& err. code== 'ENOENT' ) {
res. writeHead ( 403 )
res. write ( '403 FORBIDDEN' )
res. end ( )
}
res. writeHead ( 200 , { 'Content-type' : 'text/html' } )
res. write ( data)
res. end ( )
} )
}
if ( req. url== '/index' ) {
fs. readFile ( './node6().htm' , { encoding: 'utf-8' } , function ( err, data) {
res. writeHead ( 200 , { 'Content-type' : 'text/html' } )
res. write ( data)
res. end ( )
} )
}
}
if ( req. method. toLowerCase ( ) == 'post' ) {
if ( req. url== '/login' ) {
var data= ''
req. on ( 'data' , function ( shuju) {
data = shuju. toString ( )
} )
req. on ( 'end' , function ( ) {
var queryObj= querystring. parse ( data)
if ( queryObj. username== 'admin' && queryObj. password== '123' ) {
res. setHeader ( 'Set-cookie' , [ 'username=' queryObj. username '; ' , 'password=' queryObj. password] )
res. writeHead ( 302 , { Location: '/index' } )
res. end ( )
}
else {
res. writeHead ( 403 )
res. write ( '403 FORBIDDEN' )
res. end ( )
}
} )
}
}
} )
server. listen ( 3000 )
Http模块重定向及范例
const http = require ( 'http' )
var server = http. createServer ( function ( req, res) {
console. log ( req. url)
if ( req. url == '/kanshipin' ) {
res. writeHead ( 302 , { Location: 'http://www.bilibili.com' } )
res. write ( )
res. end ( )
}
} )
server. listen ( 3006 )
Http模块实现爬虫
const https = require ( 'https' )
const fs= require ( 'fs' )
var patupian = function ( i) {
var request= https. request ( {
protocol: 'https:' ,
host: 'ii.hywly.com' ,
port: 443 ,
method: 'get' ,
path: '/a/1/22523/' i '.jpg' ,
headers: {
}
} )
request. on ( 'response' , function ( res) {
var arr= [ ]
res. on ( 'data' , function ( chunk) {
console. log ( chunk)
arr. push ( chunk)
} )
res. on ( 'end' , function ( ) {
console. log ( arr)
fs. writeFile ( './爬虫图片/' i '.jpg' , Buffer. concat ( arr) , function ( ) {
console. log ( '图片写入成功' )
} )
} )
} )
request. end ( )
}
for ( var i= 1 ; i< 27 ; i ) {
patupian ( i)
}
--End--