您当前的位置:首页 > 计算机 > 编程开发 > Html+Div+Css(前端)

在 Express 渲染生成 HTML 页面

时间:12-14来源:作者:点击数:
CDSY,CDSY.XYZ

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`);
});
CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐