node.js - 我们可以使用NGINX作为模板引擎的Web应用程序吗

标签 node.js templates nginx

我对基本 html 模板 webapp 有一个要求,例如:

http://localhost:3000/myapp?param1=hello&param2=John被调用它应该返回 text/html 响应,如下所示:

<html>
<body>
    <p>Nice to see you John. Platform greets you "hello".</p>
</body>
</html>

名称和问候语是从参数模板化的。所以模板是这样的:

 <html>
 <body>
     <p>Nice to see you {{param1}}. Platform greets you "{{param2}}".</p>
 </body>
 </html>

我目前已经使用express.js在 Node 服务器中完成了此操作,然后服务器通过nginx.conf公开公开:

server {
    listen 80;
    # server_name example.com;

    location / {
        proxy_pass http://private_ip_address:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

我想知道是否可以使用一些插件或其他配置使用裸 nginx,而不在 3000 端口上托管 Node 服务器。

最佳答案

我能够仅使用 Nginx 使用 OpenResty 的 lua 模块对其进行编程来解决这个问题。

https://github.com/openresty/lua-nginx-module提供了在 nginx.conf 中进行编程的能力,其中可以使用现有的 lua 库,例如 https://github.com/bungle/lua-resty-template用于模板!

myapp.lua:

local template = require("resty.template")
local template_string = ngx.location.capture("/templates/greet.html")
template.render(template_string.body, {
    param1 = ngx.req.get_uri_args()["param1"],
    param2 = ngx.req.get_uri_args()["param2"]
})

问候.html:

<html>
<body>
     <p>Nice to see you {{param1}}. Platform greets you "{{param2}}".</p>
</body>
</html>

nginx.conf:

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    root ./;
    server {
        listen 8090;

    location /myapp {
        default_type text/html;
        content_by_lua_file ./lua/myapp.lua;
    }
}

content_by_lua_file 是 openresty 的强大之处。

我在这里描述了完整的过程:https://yogin16.github.io/2018/03/04/nginx-template-engine/

希望有人会觉得这有帮助。

关于node.js - 我们可以使用NGINX作为模板引擎的Web应用程序吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48577858/

相关文章:

node.js - Node.js 中的 PostgreSQL 多行更新

html - 使用 Sinatra 布局生成模板 : Yields stringified version of my html

docker - 多个 docker nginx 容器或单个 nginx docker 容器

angular - 使用Docker构建Angular失败:nginx.conf-没有这样的文件

node.js - 使用 Dialogflow REST API V2 自动注释训练短语,同时批量更新它们

javascript - Angular JS 自动更新事件 View

c++ - has_type 模板为 struct type {} 返回 true;

c++ - 如何在广义 inttype 上设置/检查 msb?

ssl - 如何让nginx为多个虚拟主机做SSL透传?

node.js - Mongoose 在docker中连接到mongo