Node.js 如何获取ejs页面的html字符串并将其值存储在ExpressJS中的字符串中?
我希望下面的控制器返回一个html字符串作为响应。目前我正在控制器中硬编码字符串,我觉得这不是正确的方法Node.js 如何获取ejs页面的html字符串并将其值存储在ExpressJS中的字符串中?,node.js,express,ejs,Node.js,Express,Ejs,我希望下面的控制器返回一个html字符串作为响应。目前我正在控制器中硬编码字符串,我觉得这不是正确的方法 router.get('/', function(req, res) { var employeeDetails; // JSON File Containing Details // I need ejs to build the page using employeeDetails and store that as a // string and retur
router.get('/', function(req, res) {
var employeeDetails; // JSON File Containing Details
// I need ejs to build the page using employeeDetails and store that as a
// string and return this string as the response
});
据我所知,你的问题可能是一个解决方案。 您可以呈现页面并将json作为对象发送,在前端使用ejs呈现它们
router.get('/', function(req, res) {
var employeeDetails; // JSON File Containing Details
employeeDetails=employeeDetails.parse;
res.render('your site',{data:employeeDetails});
});
试试这个?如果模板是字符串,可以调用
ejs.render(template)
您必须首先将模板文件作为字符串读取,因此最终会执行以下操作:
import * as ejs from 'ejs';
import { readFile as _readFile } from 'fs';
import { promisify } from 'util';
const readFile = promisify(_readFile);
router.get('/', async function(req, res) {
const template = await readFile(/* your template */, 'utf-8');
const employeeDetails = await readFile(/* your json file */, 'utf-8');
const html = ejs.render(template, { /* your data */ });
// now you have your rendered html as a string
// and can e.g.:
res.send(html);
});
可能与否重复,我想发送html字符串作为响应。不希望显示包含数据的页面。如果您说出您打算如何处理此html字符串,我可能可以提供帮助