-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
87 lines (77 loc) · 1.88 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const { readFileSync } = require("fs");
const { createServer } = require("http");
const { parse } = require("url");
const { renderToString } = require("react-dom/server");
const React = require("react");
const pizzas = [
{
name: "Focaccia",
price: 6,
},
{
name: "Pizza Margherita",
price: 10,
},
{
name: "Pizza Spinaci",
price: 12,
},
{
name: "Pizza Funghi",
price: 12,
},
{
name: "Pizza Prosciutto",
price: 15,
},
];
function Home() {
return (
<div style={{ backgroundColor: "gray", height: "100dvh" }}>
<h1>🍕 Fast React Pizza Co.</h1>
<p>This page has been rendered with React on the server 🤯</p>
<h2>Menu</h2>
<ul>
{pizzas.map((pizza) => (
<MenuItem pizza={pizza} key={pizza.name} />
))}
</ul>
</div>
);
}
function MenuItem({ pizza }) {
return (
<li>
<h4>
{pizza.name} (${pizza.price})
</h4>
<Counter />
</li>
);
}
function Counter() {
const [count, setCount] = React.useState(0);
return (
<div>
<button onClick={() => setCount((c) => c + 1)}>+1</button>
<span>{count}</span>
</div>
);
}
const htmlTemplate = readFileSync(`${__dirname}/index.html`, "utf-8");
const clientJS = readFileSync(`${__dirname}//client.js`, "utf-8");
const server = createServer((req, res) => {
const pathName = parse(req.url, true).pathname;
if (pathName === "/") {
const renderedReact = renderToString(<Home />);
const html = htmlTemplate.replace("%%%CONTENT%%%", renderedReact);
res.writeHead(200, { "Content-type": "text/html" });
res.end(html);
} else if (pathName === "/client.js") {
res.writeHead(200, { "Content-type": "application/javascript" });
res.end(clientJS);
} else {
res.end("The URL cannot be found");
}
});
server.listen(8000, () => console.log("Listening for request on port 8000"));