Express 可以轻松地从 JavaScript 字符串或文件呈现纯 HTML。 给定一个 HTML 字符串,你需要做的就是调用 res.send(),Express 负责设置 content-type 给网页头部:
const html = '<h1>Hello, World!</h1>';
const express = require('express');
const app = express();
app.get('*', (req, res) => {
// That's all you need to do! If you pass a string to `res.send()`,
// Express sets the response-type header to `text/html`
res.send(html);
});
const server = await app.listen(3000);
// Example of using the server
const axios = require('axios');
const res = await axios.get('http://localhost:3000');
res.headers['content-type']; // 'text/html; charset=utf-8'
res.data; // '<h1>Hello, World!</h1>'
如果您的 HTML 在文件中 test.html,而不是字符串,您可以使用 Express sendFile() 功能 。 唯一需要注意的是,您 必须 指定绝对路径 test.html。
app.get('*', (req, res) => {
// `__dirname` contains the directory that this code is in.
res.sendFile(`${__dirname}/test.html`);
});
