我们可以使用NGINX作为模板引擎的webapp

问题描述 投票:0回答:2

我需要基本的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的节点服务器中完成此操作,然后通过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.js templates nginx
2个回答
1
投票

您无法使用nginx呈现文件。

只需使用nginx发送文件,然后在文件内部重写指令只包含一些javascript,用查询参数替换文本内容

Nginx conf:

    location / {
        rewrite ^ /static/index.html break;
    }

index.html的:

<div>My content <span id="name"></span></div>
<script>



function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

document.getElementById("name").textContent = getParameterByName("foo"):

</script>

1
投票

我只能使用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"]
})

greet.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/

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

© www.soinside.com 2019 - 2024. All rights reserved.