如何使用 node.js 更改前端 html

Dan*_*Liu 6 jquery node.js express

所以我想从我的 node.js 后端对我的前端 html 文件进行更改。我该怎么做?(任何带有示例的建议将不胜感激)

这是我想改变它的地方:

router.post('/change', function(req, res){
    console.log(req.body.list);
    //modify html DOM here!!
    //preferably using jQuery
})
Run Code Online (Sandbox Code Playgroud)

ell*_*oM8 5

您无法按照我认为您正在尝试的方式从节点端进行修改。您可以向客户端发回响应,在该响应上,您可以触发一个函数(您可以在 JQuery 中编写),该函数将更改 DOM 并将需要更改的内容保存在本地存储中......这是一个例子 ...

//server.js
router.post('/change',function(req,res){

    // the message being sent back will be saved in a localSession variable
    // send back a couple list items to be added to the DOM
    res.send({success: true, message: '<li>New list item number 1</li><li>New list item number 2</li>'});
});
Run Code Online (Sandbox Code Playgroud)

这里是前端...

//index.html
//body
<h1>Hello World</h1>
    <ul>
        <li>List item 1</li>
         //li items with class change will be changed on button click
        <li class='change'>List item 2</li>
        <button class="trigger">Trigger Change</button>
    </ul>

<script>

   //if we have data stored in the session variable, then use the data to change the DOM text
    if(window.localStorage.permanentData){
        $('li.change').replaceWith(window.localStorage.permanentData);
    }

    //change DOM function
    function changeDom(){
        //ajax call
         $.ajax({
                  url: 'http://localhost:8080/change',
                  method:'POST',
                  data: {list: "some info"}
                }).done(function(data){
                    //if we have a successful post request ... 
                    if(data.success){
                        //change the DOM &
                        //set the data in local storage to persist upon page request
                        localStorage.setItem("permanentData", data.message);
                        var savedText = localStorage.getItem("permanentData");
                        $('li.change').replaceWith(savedText);

                        return;
                    }
                }).fail(function(){
                   //do nothing ....
                    console.log('failed...');
                    return;
                });
        };

    //trigger change DOM  function
    $('.trigger').click(function(){
        changeDom();
    });

</script>
Run Code Online (Sandbox Code Playgroud)