本文共 2197 字,大约阅读时间需要 7 分钟。
url.parse() 是 Node.js 中用于解析 URL 的一个核心模块。该函数可以将 URL 分解为多个部分,包括 host、path、query 等。第二个参数 setUrlParsing 可以启用 URL 的解析功能,返回一个包含查询字符串的对象。这种方式非常适合处理带有 query 参数的 URL。
留言板的 HTML 结构基于 Bootstrap 框架,主要包含以下组件:
在留言板中,用户通过 post.html 表单提交留言信息。表单的 action 属性指定了提交 URL 为 /pinglun,method 为 get。提交时,表单控件需包含 name 属性,以便服务器端识别字段。
未匹配的 URL 会返回 404.html 错误页面。
const http = require('http')const fs = require('fs')const template = require('art-template')const url = require('url')const comments = [ { name: 'zep', message: '今天天气真不错', dateTime: '2021.3.23' }, // 其他留言...]const server = http.createServer((req, res) => { const parseObj = url.parse(req.url, true) const pathname = parseObj.pathname if (pathname === '/') { fs.readFile('./views/index.html', (err, data) => { if (err) return res.end('404 Not Found.') const htmlStr = template.render(data.toString(), { comments }) res.end(htmlStr) }) } else if (pathname === '/post') { fs.readFile('./views/post.html', (err, data) => { if (err) return res.end('404 Not Found.') res.end(data) }) } else if (pathname.startsWith('/public')) { fs.readFile('.' + pathname, (err, data) => { if (err) return res.end('404 Not Found.') res.end(data) }) } else if (pathname === '/pinglun') { const query = parseObj.query const comment = { ...query, dateTime: '2021-03-22 23:10:15' } comments.unshift(comment) res.statusCode = 302 res.setHeader('Location', '/') res.end() } else { fs.readFile('./views/404.html', (err, data) => { if (err) return res.end('404 Not Found.') res.end(data) }) })}).listen(3000, () => { console.log('Server run...')})
转载地址:http://qhag.baihongyu.com/