Node.js 提供的 HTML 页面服务
到目前为止,我们已经直接从响应对象的 send(0 函数发送 HTML 代码。为了发送较大的代码,我们肯定需要一个单独的文件来存储 HTML 代码。
sendFile() 函数−
响应对象提供了一个 sendFile() 函数来向客户端返回一个 HTML 文件。
如何在 sendFile() 中提供 HTML 文件的路径?
我们导入 node.js 的 path 核心模块。
const path = require(‘path’);
path 有一个 join 函数。__dirname 是一个全局变量,保存着项目主文件夹的实际路径。
path.join(__dirname, ‘views’, ‘add-user.html’); 这将指向 add-user HTML 代码的实际文件位置。
App.js
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use('/test',route);
app.use((req, res,next)=>{
res.status(404).send('<h1> Page not found </h1>');
});
const server = http.createServer(app);
server.listen(3000);route.js
const path = require('path');
const express = require('express');
const router = express.Router();
router.get('/add-username', (req, res,next)=>{
// res.send('<form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>'); res.sendFile(path.join(__dirname, 'views', 'add- user.html'));
});
router.post('/post-username', (req, res, next)=>{
console.log('data: ', req.body.username);
res.send('<h1>'+req.body.username+'</h1>');
});
module.exports = router;add-user.html
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form> </body> </html>
在运行 app: npm start 后
浏览器输出:localhost:3000/test/add-username

通过使用 path 模块,它可以在任何类型的操作系统上工作,而不会出错。每个操作系统都有不同的处理路径的方法,所以 path 模块会处理好它。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP