NodeJS
Web服务
HTTP
代码示例:
// server.js
const http = require('http')
// 创建Web服务
http.createServer((req, res) => { // 接收浏览器传输过来的参数,返回渲染的内容
//req:接收浏览器传过来的参数,res:返回渲染的内容
// res.write('Hello World!') // 往浏览器中输出内容
res.writeHead(200, {'Content-Type':'text/html;charset=utf-8'}) // 状态码与响应内容的数据类型
res.write(`
<html lang="zh-CN">
<h1>小时雨</h1>
</html>
`) // 响应的内容
res.end() // 结束本次会话
}).listen(3000, () => { // 端口
console.log('server start') // 创建成功时执行
})
// module/renderHTML.js
function renderHTML(url) {
switch (url) {
case '/home':
return `
<html lang="zh-CN">
<h1>h1</h1>
</html>
`
case '/list':
return `
<html lang="zh-CN">
<h2>h2</h2>
</html>
`
case '/api/list':
return `['aaa', 'bbb', 'ccc']`
case '/api/home':
return `{name: '时雨'}`
default:
return `
<html lang="zh-CN">
<h1>404</h1>
</html>
`
}
}
module.exports = {
renderHTML
}
// module/renderStatus.js
function renderStatus(url) {
let arr = ['/home', '/list', '/api/list', '/api/home']
return arr.includes(url) ? 200 : 404
}
module.exports = {
renderStatus
}
// server.js
const http = require('http')
const moduleRenderHTML = require('./module/renderHTML')
const moduleRenderStatus = require('./module/renderStatus')
http.createServer((req, res) => {
res.writeHead(moduleRenderStatus.renderStatus(req.url), {'Content-Type': 'text/html;charset=utf-8'})
if (req.url === '/favicon.ico') { // 当请求此路径时
return // 处理不了此路径
}
res.write(moduleRenderHTML.renderHTML(req.url))
res.end()
}).listen(3000, () => {
console.log('server start')
})
// 第二种写法
// const server = http.createServer()
//
// server.on('request', (req, res) => {
// res.writeHead(moduleRenderStatus.renderStatus(req.url), {'Content-Type': 'text/html;charset=utf-8'})
// if (req.url === '/favicon.ico') {
// return
// }
// res.write(moduleRenderHTML.renderHTML(req.url))
// res.end()
// })
//
// server.listen(3000, () => {
// console.log('server start')
// })
补充
代码示例:
// server.js
const http = require('http')
const url = require("url")
http.createServer((req, res) => {
const urlObj = url.parse(req.url, true)
// console.log(urlObj.query.callback)
switch (urlObj.pathname) {
case '/api/foo':
return res.end(`${urlObj.query.callback}(${JSON.stringify({name: 'HQSY'})})`)
default:
res.end('404')
}
}).listen(3000)
// server.js
const http = require('http')
const url = require("url")
http.createServer((req, res) => {
const urlObj = url.parse(req.url, true)
res.writeHead(200, {
'Content-Type': 'application/json;charset=utf-8',
'access-control-allow-origin': '*' // 允许任何域请求
})
switch (urlObj.pathname) {
case '/api/foo':
return res.end(`${JSON.stringify({name: 'HQSY'})}`)
default:
res.end('404')
}
}).listen(3000)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
const oscript = document.createElement('script')
oscript.src = 'http://localhost:3000/api/foo?callback=test'
document.body.appendChild(oscript)
function foo(obj) { // 提前定义
console.log(obj)
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
fetch('http://localhost:3000/api/foo')
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err))
</script>
</body>
</html>
get
代码示例:
// server.js
const http = require('http')
const https = require('https')
const url = require("url")
function httpGet(cb) {
let data = ''
https.get(``,
(res) => {
res.on('data', (chunk) => { // 逐帧收集数据
data += chunk
})
res.on('end', () => {
console.log(data)
cb(data)
})
})
}
http.createServer((req, res) => {
const urlObj = url.parse(req.url, true)
res.writeHead(200, {
'Content-Type': 'application/json;charset=utf-8',
'access-control-allow-origin': '*'
})
switch (urlObj.pathname) {
case '/api/foo':
// 扮演中间人(请求另一个域的数据)
return httpGet((data) => {
res.end(data)
})
default:
res.end('404')
}
}).listen(3000)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
fetch('http://localhost:3000/api/foo')
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err))
</script>
</body>
</html>
post
代码示例:
// server.js
const http = require('http')
const https = require('https')
const url = require("url")
function httpPost(cb) {
let data = ''
const options = {
hostname: '',
post: '443',
path: '/foo',
method: 'POST',
headers: {
'Content-Type': 'application/json' // 发送的数据格式
}
}
const req = https.request(options, (res) => {
res.on('data', chunk => {
data += chunk
})
res.on('end', () => {
cb(data)
})
})
// req.write('name=HQSY&age=24')
req.write(JSON.stringify([{},{"foo":{"bar":1}}])) // 发出请求
req.end()
}
http.createServer((req, res) => {
const urlObj = url.parse(req.url, true)
res.writeHead(200, {
'Content-Type': 'application/json;charset=utf-8',
'access-control-allow-origin': '*'
})
switch (urlObj.pathname) {
case '/api/foo':
return httpPost((data) => {
res.end(data)
})
default:
res.end('404')
}
}).listen(3000)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
fetch('http://localhost:3000/api/foo')
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err))
</script>
</body>
</html>
爬虫
代码示例:
// server.js
const http = require('http')
const https = require('https')
const url = require("url")
const cheerio = require('cheerio')
function httpGet(cb) {
let data = ''
https.get(``,
(res) => {
res.on('data', (chunk) => {
data += chunk
})
res.on('end', () => {
console.log(data)
cb(data)
})
})
}
function spider(data) {
let $ = cheerio.load(data)
let $moviewList = $('.column.content')
// console.log($moviewList)
let movies = []
$moviewList.each((index, value) => {
movies.push({
title: $(value).find('.title').text(),
grade: $(value).find('.grade').text(),
actor: $(value).find('.actor').text()
})
})
console.log(movies)
return JSON.stringify(movies)
}
http.createServer((req, res) => {
const urlObj = url.parse(req.url, true)
res.writeHead(200, {
'Content-Type': 'application/json;charset=utf-8',
'access-control-allow-origin': '*'
})
switch (urlObj.pathname) {
case '/api/foo':
return httpGet((data) => {
res.end(spider(data))
})
default:
res.end('404')
}
}).listen(3000)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
fetch('http://localhost:3000/api/foo')
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err))
</script>
</body>
</html>