【问题标题】:How to display a variable in html generated with node.js如何在使用 node.js 生成的 html 中显示变量
【发布时间】:2019-09-14 19:47:48
【问题描述】:

出于培训目的,我试图在我的 html 页面中显示部分路径名。

例如,如果 URL 是这样的:http://localhost:8080/firstname/abcd
我希望我的浏览器显示:"Hello abcd"

const config = require('./config');
var http = require('http');
var url = require('url'); 

var server = http.createServer(function(req, res) {

var path = url.parse(req.url).pathname;

    if(path.includes('firstname'))
    {
        firstname = path.replace('/firstname/', '');

        res.writeHead(200, {"Content-Type": "text/html"});
        res.write('<!DOCTYPE html>'+
            '<html>'+
            '    <head>'+
            '        <meta charset="utf-8" />'+
            '        <title>Node.js tests</title>'+
            '    </head>'+ 
            '    <body>'+
            '       <p id = "name"></p>'+
            '    </body>'+
            '<script type="text/javascript">
            'document.getElementsById("name").innerHTML = ("Hello " + firstname)'+
            '</script>'+
            '</html>');
        res.end();
    }
    else
    {
        console.log('Nothing to display');
    }
});
server.listen(config.env.port);

如您所料,页面显示为空。

【问题讨论】:

  • "document.getElementsById" 这是错误的应该是"document.getElementById",即's'不应该在那里。
  • 你是对的 uday214125。在这之前,我一直在使用 getElementsByTagName 进行测试。但奇怪的是,ElementsById 似乎也在工作。无论如何,我也会解决这个问题,谢谢。

标签: javascript html node.js


【解决方案1】:

如果您只想显示除firstname 部分之外的路径,则:

var server = http.createServer(function(req, res) {

var path = url.parse(req.url).pathname;

    if(path.includes('firstname'))
    {
        let firstname = path.replace('/firstname/', '');
        res.writeHead(200, {"Content-Type": "text/html"});
        res.write('<!DOCTYPE html>'+
        '<html>'+
        '    <head>'+
        '        <meta charset="utf-8" />'+
        '        <title>Node.js tests</title>'+
        '    </head>'+ 
        '    <body>'+
        '       <p id = "name">'+
              'hello ' + firstname +
              '</p>'+
        '    </body>'+            
        '</html>');
    }
    else
    {        
        res.write('Nothing to display');
    }
    res.end();
});
server.listen(config.env.port);  

转到http://localhost:8080/firstname/abcd 会得到Hello abcd

【讨论】:

    【解决方案2】:

    为什么要在 HTML 中使用 js 代码?

    您可以呈现静态 HTML 页面并将其作为响应发送。 像这样:

    ...
            res.write('<!DOCTYPE html>'+
                '<html>'+
                '    <head>'+
                '        <meta charset="utf-8" />'+
                '        <title>Node.js tests</title>'+
                '    </head>'+ 
                '    <body>'+
                `       <p id = "name">Hello ${firstname}</p>`+
                '    </body>'+
                '</html>');
    ...
    

    【讨论】:

    • 谢谢你!但它在页面上显示 Hello ${firstname} :(
    猜你喜欢
    • 2015-11-05
    • 2015-02-16
    • 1970-01-01
    • 2013-05-12
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    相关资源
    最近更新 更多