首页 > 解决方案 > 如何在 node.js 中创建路由并包含 html 代码

问题描述

我带着一些关于 Node.Js 的问题回到这里。我是 Node 的新手,我正在尝试编写一些代码来创建服务器,然后在页面之间创建一些路由。

为了创建路由,我是否必须将 html 文件转换为 hbs?

所以基本上,有没有可能包含 html 页面或文件,而不是 html 标签?

另外,对于 CSS,我需要做些什么还是应该自动包含它?

我认为,为了在页面之间创建路由,我需要检查 URL?

我是否需要单独的文件,我应该在其中为 GET 和 POST 方法创建一些代码?我不太确定。

如果我使用 WebStorm 并创建一个 Node.Js Express 项目,它会创建一个文件夹“bin”,其中有一个文件“www”。这个文件是什么?

亲切的问候,G

//code for the server:

var http = require('http');
const express = require('express')
const app = express()
const port = 3000

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' }); // http header
    var url = req.url;

    if (url === '/'){
        res.write(`<h1>home page</h1>`); //write a response
        res.end(); //end the response
    } else if (url === '/index') {
        res.write('<h1>index page<h1>'); //write a response
        res.end(); //end the response
    } else if (url === '/test') {
        res.write('<h1>test page<h1>'); //write a response
        res.end(); //end the response
    } else if (url ==='/contact'){
        res.write('<h1>contact page<h1>'); //write a response
        res.end(); //end the response
    } else if (url ==='/about'){
        res.write('<h1>about page</h1>'); // write a response
        res.end(); //end the response
    }
}).listen(port, function () {
    console.log(`server start at portL ${port}`); //the server object listens on port 3000
}); 

标签: javascripthtmlnode.js

解决方案


我觉得你需要的是一个渲染引擎。您可以使用hbs npm 模块,这是一个基于handlebars.js的小型且易于使用的视图引擎。

您需要先安装hbs

$ npm install hbs --save

然后确保您的文件夹结构是这样的:

├── package-lock.json
├── package.json
├── server.js
└── views
    ├── about.hbs
    ├── contact.hbs
    └── home.hbs

还有你的server.js文件,像这样:

const path = require('path')
const express = require('express')
const hbs = require('hbs')

const app = express()
const port = 3000

// Configure view engine and set views folder

app.set('view engine', 'hbs')
app.set('views', path.join(__dirname, 'views'))

// Manage the routes

app.get('/', (req, res) => {
    res.render('home')
})

app.get('/about', (req, res) => {
    res.render('about')
})

app.get('/contact', (req, res) => {
    res.render('contact')
})

// Start the server

app.listen(port, () => {
    console.log(`The server is running on port ${port}.`)
})

这样,使用hbs 视图引擎,您还可以将数据从服务器传递到您的 HTML 内容,如下所示:

app.get('/about', (req, res) => {
    const data = { name: 'John Doe' }
    res.render('about', data)
})

按照这个示例,您将在 /views/about.hbs文件中捕获从服务器发送的数据,如下所示:

<div>
    <h1>Hello, {{name}} how are you today?</h1>
</div>

希望这对您有所帮助。

编辑:

要引用 CSS 文件,您必须在 Node.js 服务器上创建一个静态目录。为此,请将其添加到您的server.js文件中:

app.use('/public', express.static(__dirname + '/public'));

然后确保您创建一个/public文件夹并将您的资产移动到那里,如下所示:

├── server.js
└── public
    ├── bundle.css
    └── logo.png

之后,您现在可以从视图中引用所有静态内容。例如在您的home.hbs中:

<!-- Reference static CSS files -->
<link href="/public/bundle.css" rel="stylesheet">

<!-- Reference static images -->
<img src="/public/logo.png" alt="" />

如果您不想使用视图引擎而只想呈现纯 HTML 文件,您也可以这样做:

app.get('/contact', (req, res) => {
    res.sendFile(path.join(__dirname + '/views/contact.html'));
});

推荐阅读