【发布时间】:2021-11-26 06:09:56
【问题描述】:
我有一个与从节点 js 渲染 HTML 相关的问题。
我正在创建动态 HTML(他们目前正在使用 Reactj 概念),但我不知道如何像 Reactjs 在我的节点 js 服务器上那样做。 https://es.reactjs.org/docs/rendering-elements.html
我用过:
const express = require ('express')
const app = express ()
const port = 3000
// app.use (express.static ("public"))
app.listen (port, () => {
console.log (`Example app listening at http: // localhost: $ {port}`)
})
我已经读到,如果你使用 app.use (express.static ..,它只会加载静态文件。
所以我决定添加一个端点,将网站转换为动态:
app.get ("/", (req, res) => {
res.send ("<html> <head> </head> <body> <h1> .... </h1> </body> </html>");
});
问题是我需要将“index.html”传递给纯文本,用 DOM 读取它并通过 DOM 添加或删除元素(文本) 最后返回整个html页面。
1 - Pass the html to text.
2 - Cycle that text by dom
3 - Add or remove items
3.1 - Add divs inside other containers "through an id" by DOM
app.get ("/", (req, res) => {
res.send (stringTextHtmlWebPage);
// The problem is that I have to return the entire directory like
// app.use(express.static ("public")) does; but with the modified file.
});
在 Reactj 中,他们做了类似的事情。他们用 ReactDOM.render 注入。 他们有一个:
index.js
function App () {
return (<div className = "container mt-5"> ... </div>);
// I was surprised by this line, it goes without any quotes ... and it works ...
}
ReactDOM.render (
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById ('root') // element from public / index.html
);
Index.html
<body>
<noscript> You need to enable JavaScript to run this app. </noscript>
<div id = "root"> </div>
在我的情况下,如何返回整个 HTML 页面。使用我指示的步骤?
编辑:
我必须返回整个目录的文件。 (但有些修改有些没有) 例如: 我修改了 index.html,但它关联了一个 css、js、bootstrap ...... 它必须像“app.use (express.static (" public "));”一样工作但有一些修改过的文件。 简单来说就是使用node js修改一个文件然后调用app.use(express.static("public"));并且这个文件被修改了。 (类似于 React 所做的)
// Modify file
// calls app.use (express.static ("public")); (with the modification)
或者有什么方法可以将代码注入到我的“app”变量中? 一些风格
app.injectPath ("public / index.html"). Tour_the_DOM (tag ["tag1"]) = "<div> add this div </div>";
就像 React 一样?
我不能使用模板(pug、manillar...),因为页面的源代码写在别处。
我也读过: https://es.reactjs.org/docs/add-react-to-a-website.html 但是不知道怎么和app.use(express.static("public"))集成起来
这就是我要找的。 https://tech-wiki.online/es/react-server-side-rendering.html 但它不起作用。有什么解决方案可以做到这一点吗?
提前致谢。
【问题讨论】:
标签: javascript html node.js reactjs dom