示例代码:/lesson04/www/1.htmlhtml
<!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>
网页内容
<img src="/1.jpg" alt="">
</body>
</html>
复制代码
预期实现的结果为: a. 在浏览器访问http://localhost:8080/1.html。 b. 读取到www/1.html,由HTML文件发起对www/1.jpg的请求。 c. 网页中显示HTML内容和图片。前端
使用Nodejs实现服务端代码:git
示例代码:/lesson04/server.jsgithub
const http = require('http')
const fs = require('fs')
const server = http.createServer((request, response) => {
console.log(request.url) // 在request对象中,能够获取请求的URL,经过URL判断请求的资源。
fs.readFile(`./www${request.url}`, (error, buffer) => { // 根据URL查找读取相应的文件。
if (error) { // 若读取错误,则向前端返回404状态码,以及内容Not Found。
response.writeHead(404)
response.write('Not Found')
} else { // 若读取成功,则向前端返回读取到的文件。
response.write(buffer)
}
response.end() // 关闭链接。
})
})
server.listen(8080)
复制代码
接下来的文章中,将进入先后段的数据交互内容。数据库