你写的 php 代码可能只是 php 的 html 模板版本(因为缺少更好的术语……)
当在浏览器中请求一个 .php 页面时,会调用一个 php 解释器来解析 html 中的 php 标签并将其替换为 html/text。然后将该结果发送到浏览器。
node.js 不能那样工作。
Node.js 比 php 更详细......当谈到这个特定主题时。 node.js 不仅仅是一个 Web 应用程序框架或 Web 服务器,它还可以用作各种可执行文件来运行常见任务。
通常,要获得您在 node.js 中寻找的那种功能,您会使用一个模板框架,例如把手和 express 来处理网络服务器和路由。这是一个例子:
// this is just an example, it may or may not work, I did not test it.
var express = require('express'),
app = express(),
exphbs = require('express-handlebars'),
hbs,
path = require('path');
// serve all files under the /assets folder as static files
app.use('/assets', express.static(path.join(__dirname, '/assets')));
// handlebar engine config
hbs = exphbs.create({
defaultLayout: 'main'
});
// attach engine and specify view location
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, '/views'));
// home page http://domain.com/
app.get('/', function (req, resp) {
resp.render('home', {title: 'Home | Hello World!', text: 'Welcome to my site!'});
});
// start webserver
app.listen(3000);
上述节点应用程序将创建一个监听端口 3000 的网络服务器,以响应对/assets 和/ 的请求。当请求/ 时,来自/views 文件夹的home.handlebars 视图将使用来自/views/layouts 的main.handlebars 布局呈现这是一个示例视图,它将显示为/ 传递的标题上面创建的路线:
/views/layouts/main.handlebars
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>{{title}}</title>
</head>
<body>
{{{body}}}
</body>
</html>
/views/home.handlebars
<h1>Hello World!</h1>
<p>{{text}}</p>