- Full-Stack React Projects
- Shama Hoque
- 153字
- 2021-06-25 21:45:05
Serving an HTML template at a root URL
With a Node, Express, and MongoDB enabled server now running, we can extend it to serve an HTML template in response to an incoming request at the root URL /.
In the template.js file, add a JS function that returns a simple HTML document that will render Hello World on the browser screen.
mern-skeleton/template.js:
export default () => {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MERN Skeleton</title>
</head>
<body>
<p id="root">Hello World</p>
</body>
</html>`
}
To serve this template at the root URL, update the express.js file to import this template, and send it in the response to a GET request for the '/' route.
mern-skeleton/server/express.js:
import Template from './../template'
...
app.get('/', (req, res) => {
res.status(200).send(Template())
})
...
With this update, opening the root URL in a browser should show Hello World rendered on the page.
If you are running the code on your local machine, the root URL will be http://localhost:3000/.