简体   繁体   English

如何使用 node js 更改 HTML 内容

[英]How can I change HTML content by using node js

I want to change my HTML file (index.html) content bellow我想在下面更改我的 HTML 文件 (index.html) 内容

<html>
<body>
   <div id="greeting">Hello world</div>
</body>
</html>

to something else, by doing this in backend (Node js).通过在后端(Node js)中执行此操作来实现其他目的。 Here is nodejs code:这是 nodejs 代码:

var express = require("express");
var app = express();
var server = require('http').createServer(app);

app.get('/', function (req, res, ext) {
    res.sendFile(__dirname + '/public/index.html');
});

app.use(express.static('public'));

server.listen(8000);

Sorry for my English, if my words are not clear.如果我的话不清楚,对不起我的英语。

The simplest way to change the content of your更改内容的最简单方法

<div id="greeting">Hello world</div>

Would be to create an Index.js and将是创建一个 Index.js 和

import React from 'react'
import ReactDOM from 'react-dom'


const theDiv = document.getElementById("greeting")

function NewContent(props){
    return(
        <div>
            New Content
        </div>
    )
}

ReactDOM.render(<NewContent/>, theDiv)
  1. I have imported react and react dom我已经导入了 react 和 react dom
  2. i have grabbed the greeting div and placed it inside of a "theDiv"我抓住了问候 div 并将其放在“theDiv”中
  3. I have created a react Component called NewContent我创建了一个名为 NewContent 的反应组件
  4. I then tell react to render the newContent inside of theDiv然后我告诉 react 在 theDiv 中呈现 newContent

Here's what you can do:-您可以这样做:-

Add a form to your index.html which sends a request when clicked:将一个表单添加到您的index.html ,该表单在单击时发送请求:

<html>
<body>
   <div id="greeting">Hello world</div>
   <form action="/change-content" method="POST">
    <button type="submit">Change content</button>
   </form>
</body>
</html>

In the node app you can listen to that:在节点应用程序中,您可以收听:

app.post('/', function (req, res, ext) {
    res.sendFile(__dirname + '/public/anotherFile.html');
});

so just make sure that you have another HTML file to serve when the button is clicked.所以只要确保你有另一个 HTML 文件在点击按钮时提供服务。

anotherFile.html can be anything you want anotherFile.html可以是你想要的任何东西

<html>
<body>
   <div>Node.js</div>
</body>
</html>

This is just one way to do it, typically you might want to use a better app structure and move your different HTML files into a folder.这只是一种方法,通常您可能希望使用更好的应用程序结构并将不同的 HTML 文件移动到一个文件夹中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM