原生搭建主要作为了解,真正搭建可以使用一些封装的模块express等
简单搭建
const http = require('http')
const serve = http.createServer()
serve.on('request', (request, response) => {
// 防止乱码()
response.setHeader('Content-Type', 'text/html; charset=utf-8')
response.end('返回给客户端的数据')
})
serve.listen(8090, () => {
console.log('ok')
})
可以把文件返回给客户端
const http = require('http')
const fs = require('fs')
const serve = http.createServer()
serve.on('request', (request, response) => {
//防止乱码
response.setHeader('Content-Type', 'text/html; charset=utf-8')
fs.readFile(__dirname + '/resources/jsonData.json', 'utf8', (erro, dataStr) => {
if (erro) {
return console.log('读取文件失败')
}
response.end(dataStr)
})
})
serve.listen(8090, () => {
console.log('操作成功')
})
请求对照路径形式
const http = require('http')
const serve = http.createServer()
serve.on('request', (request, response) => {
const url = request.url
const method = request.method
console.log(url)
console.log(method)
let content = '<b>404 notFound</b>'
if (url === '/' || url === '/index.html') {
content = '<h1>首页</h1>'
} else if (url === '/about.html') {
content = '<h1>关于页面</h1>'
}
// 防止乱码()
response.setHeader('Content-Type', 'text/html; charset=utf-8')
response.end(content)
})
serve.listen(8090, () => {
console.log('操作成功')
})
一些注意事项
listen()方法的第二个参数
参数为localhost或者127.0.0.1,只有本机 http://localhost:8899/和http://127.0.0.1:8899/ 可以请求到, 其余请求地址请求不到
参数为本机ipv4ip地址(例200.0.0.56),时候,不同设备同一局域网下请求 http://200.0.0.56:8899/才可以请求到 但是本机 http://localhost:8899/和http://127.0.0.1:8899/请求不到
不传参数时候默认全部未分配即所有不同设备同一局域网下请求 http://200.0.0.56:8899/可以请求到 本机 http://localhost:8899/和http://127.0.0.1:8899/也可以请求到
serve.listen(8899, () => {
console.log('ok')
})
头信息Content-Type
为了防止乱码响应对象(response)要加上Content-Type头部(application/json指的是json格式,text/html则html标签在浏览器获取后可以直接解析
response.setHeader('Content-Type', 'application/json; charset=utf-8')
备注
实现一个end()方法为一次完整的请求,end()方法为响应对象上挂载的对象,response属性,request是请求对象,response是响应对象,通过响应对象给客户端返回数据
serve.on('request', (request, response) => {
response.end()
})
工具nodemon
启动服务后每次修改完文件,首先要做的是,关掉文件重启服务,为了防止遗忘,使用nodemon模块启动文件会监听文件改动帮助我们自动重启服务
npm i nodemon -g
使用
nodemon custorm.js