如何设置非常基本的Node.js路由

458 阅读4分钟

在上一个 Node.js 教程中,我们学习了如何将一些非常基本的 html 呈现在屏幕上。当然,一个实际的网站或应用程序会有许多不同的html文件要呈现给用户。通常,你需要某种类型的路由机制来处理这个问题。在这一集,我们将看一个路由的例子,用户可以在浏览器中加载不同的url。每个不同的url将是一个不同的路由,这反过来将从node.js服务器加载一个不同的html页面。让我们看看现在如何设置非常基本的Node.js路由。


两个不同的HTML文件

我们需要至少有两个HTML文件来演示Node.js中的路由。我们将坚持使用上一课中的简单的index.html文件,同时我们将在项目中创建一个新的about.html文件。以下是这两个文件,如果你正在关注的话。


index.html

<!doctype html>
<html lang="en">

<head>
    <title>Hello, world!</title>
</head>

<body>
    <h1>Hello, world!</h1>
</body>

</html>

about.html

<!doctype html>
<html lang="en">

<head>
    <title>About Us!</title>
</head>

<body>
    <h1>Hiya Friends! This is an html file that is about us!</h1>
</body>

</html>

将路由放在一个单独的文件中

很多时候,在Node.js中,会有一个单独的文件,其中包含应用程序的所有路由。这个JavaScript文件将处理进入的http请求,并根据需要分配正确的路由。因此,让我们创建一个名为routes.js的新JavaScript文件。
nodejs routes in separate file

那么,我们要在这个routes.js文件中放什么呢?嗯,我们需要设置的是一个函数的导出,然后我们可以在主server.js文件中使用。我们可以从这个开始。


routes.js

module.exports = {
    handleRequest(request, response) {
        response.writeHead(200, {
            'Content-Type': 'text/html'
        });
    }
}

使用url模块

为了设置路由,应用程序需要知道在浏览器中输入了什么url。Node.js有一个url模块,它允许我们把一个url拆成所有可读的部分。我们将需要它来设置我们的路由,所以现在让我们把它包含在我们的routes.js文件中。

const url = require('url');

module.exports = {
    handleRequest(request, response) {
        response.writeHead(200, {
            'Content-Type': 'text/html'
        });
    }
}

配置我们的两个路由

现在我们已经准备好设置几个路由了。一个路由将加载index.html页面,另一个路由将加载about.html文件。我们这样做的方法是,首先确定路径。如果找到的路径是/ ,那么index.html将被渲染。如果路径是/about.html ,那么about.html就会被呈现出来。让我们把routes.js中的module.exports更新为以下代码。

module.exports = {
    handleRequest(request, response) {
        response.writeHead(200, {
            'Content-Type': 'text/html'
        });

        let path = url.parse(request.url).pathname;
        
        switch (path) {
            case '/':
                html.render('./index.html', response);
                break;
            case '/about':
                html.render('./about.html', response);
                break;
            default:
                response.writeHead(404);
                response.write('Route not found');
                response.end();
        }
    }
}

在上面这段代码中,我们首先通过url.parse()pathname找到我们感兴趣的路径。非常好。


使用switch 语句进行路由

现在我们有了路径,我们可以使用switch语句,根据路径变量的内容加载不同的html文件。我们可以看到,如果路径的值是'/',那么就会调用一个渲染函数,将'./index.html'文件作为一个参数。另一方面,如果路径的值是'/about.html',那么同样的渲染函数将被调用,但这次它将以'./about.html'的字符串作为参数。最后,我们设置了默认场景,它提供了任何不存在的路由。请注意,我们使用了一个ES6 Object Literal来存储我们需要的那个render() 函数。下面是我们现在的完整的routes.js文件。


routes.js

const url = require('url');
let fs = require('fs');

html = {
    render(path, response) {
        fs.readFile(path, null, function (error, data) {
            if (error) {
                response.writeHead(404);
                respone.write('file not found');
            } else {
                response.write(data);
            }
            response.end();
        });
    }
}

module.exports = {
    handleRequest(request, response) {
        response.writeHead(200, {
            'Content-Type': 'text/html'
        });

        let path = url.parse(request.url).pathname;

        switch (path) {
            case '/':
                html.render('./index.html', response);
                break;
            case '/about':
                html.render('./about.html', response);
                break;
            default:
                response.writeHead(404);
                response.write('Route not found');
                response.end();
        }
    }
}

将routes.js导入server.js中

我们需要做的最后一件事是确保将routes.js导入我们的主server.js文件中。


server.js

let http = require('http');
let router = require('./routes');

let handleRequest = (request, response) => {
    response.writeHead(200, {
        'Content-Type': 'text/html'
    });

};

http.createServer(router.handleRequest).listen(8000);

在上面的片段中,我们首先看到我们使用*let router = require('./routes');*将我们刚刚在routes.js中构建的所有逻辑直接存储到该router 。现在,当我们继续前进并创建服务器时,我们可以利用router.handleRequest 函数来实际处理这些路由。非常酷。让我们启动我们的服务器并在浏览器中进行测试。

c:node>node server.js

访问http://localhost:8000/

index-html route


访问http://localhost:8000/about

about-html route

我们甚至可以尝试访问一个像这样的胡言乱语的路由http://localhost:8000/jibberish,由于我们设置了路由来处理这个问题,我们将得到一个漂亮的错误信息。
routes not working


Node.js路由教程总结

在本教程中,我们学习了如何在Node.js中从头设置路由。这有助于我们了解Node.js工作的基本原理。在几乎所有情况下,你实际上不必在Node中设置自己的路由,因为你可以使用许多可用的框架之一,为你做所有的艰苦工作。例如,Express.js可以用来大大简化我们上面创建的内容。然而,在使用框架使事情变得更容易之前,看看如何用很长的方法来做,还是很有帮助的。