【发布时间】:2018-08-13 00:40:13
【问题描述】:
我有一个通过快速服务器提供服务的应用程序。我正在用 vanilla JavaScript 构建我的所有模板,没有任何模板文件或视图引擎。我想传递将在客户端的 JavaScript 上下文中用于正常导航请求的数据。这样做的最佳做法是什么?
我根本没有使用 AJAX 或单页应用程序。我所有的模板都在服务器上完全呈现。这是服务器的基本版本:
const express = require('express')
const app = express()
const meta = `<meta name="viewport" content="width=device-width, initial-scale=1">`
const account = `<button id="sign-out" class="js-authorized">Sign Out</button>`
const template = (title, content) => `<html>
<head>
<title>${title}</title>
${meta}
</head>
<body>
<div class='account'>
${account}
</div>
<div class='content'>
<h1>${title}</h1>
${content}
</div>
</body>`
app.get('/', (request, response) => {
const document = template('Index', 'Welcome')
// How can I send this to the client?
const data = {
mainSeed: Math().random(),
secondarySeeds: [Math().random(), Math().random(), Math().random()]
}
// This wouldn't work:
// return response.send(data, document)
return response.send(document)
})
我想确保页面上的任何 JavaScript 都可以访问数据,但我不想在服务器上使用除 JavaScript 模板文字之外的任何模板逻辑。通过基本 Express 向客户端发送数据的最佳做法是什么?
【问题讨论】:
-
找到了这个帖子,但不知道它是否没有视图引擎:stackoverflow.com/questions/21172889/…希望它会有所帮助
-
感谢您的努力,但是通过线程查看,建议的解决方案要求它是一个 AJAX 请求(我的是正常的导航请求),并且它们需要一个视图引擎,以便
render方法可以使用。
标签: javascript node.js express routing httpresponse