ip地址:标识网络上不同的设备(可联网的设备)
端口号:标识同一设备上的不同的网络进程 // 同一台设备 具有唯一性
网络进程 (可联网的,运行起来的程序)
搭建一个后端的程序
1、引入http模块
2、配置服务器程序的端口号 // 不要使用0-1024 及知名端口 mysql 3306 mongodb 27017
3、创建服务器对象
4、调用服务器对象的监听方法
// 1、引入http模块
const http = require('http')
// 2、配置服务器程序的端口号
const port = 8080
// 3、创建服务器对象
const server = http.createServer((request, response) => {
// request 请求对象 response 响应对象
// 这里代码什么时候执行?
// 每接收到一次请求就来执行一次这里的代码
// 获取请求对象相关的一些信息
// 获取请求路径
let reqUrl = request.url // 获取请求路径(请求报文中第一行的第二个信息)
console.log(reqUrl)
response.write('hello nodejs http') // 可以往浏览器书写一些响应体内容
response.end('hello nodejs') // 表示响应工作已经结束,这个方法后面不要再去写关于响应的任何操作
// write 和 end 的相同点:都可以传入参数表示往浏览器书写一定内容
// write 和 end 的不同点:write可以连续写 end表示响应结束 一般放最后
})
// 4、调用服务器对象的监听方法
server.listen(port, (error => {
console.log(error)
console.log(`webServer is listening at port ${port}`)
}))
write 和 end 的相同点:都可以传入参数表示往浏览器书写一定内容
write 和 end 的不同点:write可以连续写 end表示响应结束 一般放最后
获取get 请求参数
// 第一个参数为请求路径
let obj = url.parse(reqUrl, true)
获取 post 请求参数
const http = require('http')
const url = require('url')
const port = 8082
const server = http.createServer((request, response) => {
// 先获取用户名密码 本质上就是获取post请求的参数
// 以事件的方式来接收 事件名是data 一旦接收post 请求,就会触发这里的代码执行
request.on('data',(postData)=>{
// 一旦接收post请求,就会触发这里的代码执行
console.log(postData.toString(),'post内容')
})
})
server.listen(port, (error => {
console.log(error)
console.log(`webServer is listening at port ${port}`)
}))
实现路由监听
// 1、引入http
const http = require('http')
const fs = require('fs')
const path = require('path')
// 设置端口
const port = 8082
// 创建一个服务器对象
// 1、引入http
const http = require('http')
const fs = require('fs')
const path = require('path')
// 设置端口
const port = 8082
// 创建一个服务器对象
const server = http.createServer((request, response) => {
// 判断浏览器需要那个资源文件??
let reqUrl = request.url
if (reqUrl === '/' || reqUrl === 'index.html') {
// 读取页面内容,返回信息
let filePath = path.join(__dirname, 'index.html')
let content = fs.readFileSync(filePath)
response.end(content)
} else if (reqUrl === '/detail') {
let filePath = path.join(__dirname, 'detail.html')
let content = fs.readFileSync(filePath)
response.end(content)
} else if (reqUrl.endsWith('.css')) {
let filePath = path.join(__dirname, 'index.css')
let content = fs.readFileSync(filePath)
response.end(content)
}
// 遵循http协议 ,设置响应头
response.setHeader("Content-type", "text/html;charset=utf-8")
})
server.listen(port, (err) => {
})