English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Express.js路由定义了Express应用程序如何使用特定的URI(或path)和特定的HTTP请求方法(GET,POST等)来响应客户端请求 。
为了理解Express.js路由的需求,让我们深入一个示例。
创建一个基本的Express应用程序,如下所示。
app.js
var express = require('express') var app = express() // 서버 시작 var server = app.listen(8000, function(){ console.log('Listening on port 8000...') )
我们要做的是,实例化一个快速应用程序,在端口8000上启动它。现在,打开浏览器,并访问URL http://localhost:8000/。
响应是它无法获取资源“ /”。
即使控制台中没有错误。该应用程序运行良好。
这是为什么?因为在Express应用程序中,我们启动了服务器,但是没有定义当请求到达服务器时必须发生的情况。
这就是Express.js路由的体现。以下是一条简单的快速路线。
app.get('/', function(req, res) { res.send('This is a basic Example for Express.js by w3codebox') )
这条路线定义什么?当您收到GET请求网址为的请求时,此路由定义在函数内部执行语句/。
아래의 스크린 캡처는 요청 URL을 가진 GET 요청에 대해 기능을 실행하는 라우팅입니다./hello/。
app.js에서 몇 가지 라우팅을 정의하고 서버를 시작하겠습니다.
app.js
var express = require('express') var app = express() // GET 요청과 요청 URL 경로/또는 루트에서 실행되는 라우팅 app.get('/', function(req, res) { res.send('홈.') ) // GET 요청과 요청 URL 경로/ hello /실행된 라우팅 app.get('/hello/', function(req, res) { res.send('Hello 페이지.') ) // GET 요청과 요청 URL 경로/ 안녕히 가세요 /실행된 라우팅 app.get('/안녕히 가세요/', function(req, res) { res.send('안녕히 가세요 페이지.') ) // 서버 시작 var server = app.listen(8000, function(){ console.log('Listening on port 8000...') )
빠른 요청 시작
브라우저에서 주소를 클릭하면 됩니다. 기본적으로 브라우저는 GET 요청을 보냅니다.
URL 경로 http:// localhost:8000 /의 GET 요청
URL 경로 http:// localhost:8000 / hello /의 GET 요청
URL 경로 http:// localhost:8000 / 안녕히 가세요 /의 GET 요청
경로에서 하나나 여러 가지 기능을 제공할 수 있습니다. 각 기능은 미들웨어라고 합니다.
app.js
var express = require('express') var app = express() // 다양한 기능을 가진 빠른 경로 app.get('/hello/', function(req, res, next) { res.write('Hello page. ') next() }, function(req, res, next){ res.write('Hello again. ') res.end() ) // 서버 시작 var server = app.listen(8000, function(){ console.log('Listening on port 8000...') )
브라우저에서는 다음과 같이 출력됩니다
이 기능들을 모듈화하여 정의할 수도 있습니다. 예를 들어,
var express = require('express') var app = express() function hello(req, res, next) { res.write('Hello page. ') next() } function helloagain(req, res, next){ res.write('Hello again. ') res.end() } // 다양한 기능을 가진 빠른 경로 app.get('/hello/', hello, helloagain) // 서버 시작 var server = app.listen(8000, function(){ console.log('Listening on port 8000...') )
이 Express.js 강의에서는 Express.js 라우팅이 무엇인지, Express.js 라우팅을 어떻게 정의하며, 이러한 라우팅을 사용하여 다른 URL 경로에 대해 다양한 HTTP 메서드를 제공하는 방법을 배웠습니다.