创建一个http服务器步骤
// 引入网络通信模块
const http = require('http');
// 创建一个服务器对象
const app = http.createServer()
// 声明端口号
const port = 1024
// 绑定request事件
app.on('request', (req, res)=>{
// req: 请求对象,客户端发送来的数据封装到该对象中
// res: 响应对象,服务器用于做出回应的对象
// 服务器向客户端写数据
res.write('hello\n')
// 结束响应并传递数据
res.end('world')
})
// 启动服务器
app.listen(port, () => {
// 当服务器启动成功后,就会调用此函数
console.log(`server start: http://127.0.0.1:${port}`)
})
静态资源
什么是静态资源?
不会发生变化的资源就是静态资源,静态资源一般指不会发生变化的文件。
静态资源服务器
const http = require('http');
const path = require('path');
const fsp = require('fs/promises');
const app = http.createServer();
// 定义静态资源文件夹
const staticDirPath = path.join(__dirname, 'public')
app.on('request', (req, res) => {
// 拼接资源路径
let assetPath = path.join(staticDirPath, `.${req.url}`)
// 判断文件是否存在
fsp.stat(assetPath).then((stat) => {
// 判断当前路径是否是一个目录
if (stat.isDirectory()) {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('无效文件')
return
}
// 读取文件
fsp.readFile(assetPath).then(data => {
// data: 读出来的文件数据
res.write(data)
}).finally(() => {
res.end()
})
}).catch(reason => {
console.error(reason)
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('404资源未找到')
})
})
app.listen(80, () => {
console.log('server start on: http://127.0.0.1')
})
服务器跨域处理
const express = require('express');
const cors = require('cors')
const path = require("path");
const app = express()
// 若不记得跨域响应头有哪些,可以使用 cors 包
// app.use(cors())
// 添加一个中间件拦截所有请求
// app.all('*', (req, res, next) => {
// // 设置允许跨域的响应头
// res.setHeader('Access-Control-Allow-Origin', '*')
// res.setHeader('Access-Control-Allow-Methods', '*')
// res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
// next()
// })
app.use('/', express.static(path.join(__dirname, 'public')))
app.get('/test', (req, res) => {
res.json({msg: 'ok'})
})
app.get('/jsonp', (req, res) => {
// const {callback} = req.query
// res.setHeader('Content-Type', 'text/javascript')
// const params = {x: 1, y: 2}
// res.send(`${callback}('${JSON.stringify(params)}')`)
res.jsonp({x: 1, y: 2})
})
app.listen(80, () => {
console.log(`start on: http://127.0.0.1`)
})