Node.js Web development (b)

Previous article introduces the basic operation of koa2 (sit down sit down), but always return to the same HTML seems impossible, so now we need to deal with the URL.

Something to point directly to the high point, we need to be able to handle a URL of middleware, it is called: KOA-Router :

npm install koa-router

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
      
      
const Koa = require( 'koa');
const router = require( 'koa-router')();
const app Koa = ();
router.get( '/hello/:name', async(ctx, next) => {
var name = ctx.params.name;
ctx.response.body = `<h1>Hello, {$name}!</h1>`;
});
router.get( '/', async(ctx, next) => {
ctx.response.body = '<h1>Index Page</h1>';
});
app.use(router.routes());
app.listen( 3000);
console.log( 'Server listen on port 3000...');

The code here, will visit the URL localhost: return to Index Page 3000, while visiting localhost: 3000 / hello / louis when the display is Hello, louis, and this router is for us to achieve the ability to handle the URL!. Note, at the time of the introduction router, is one more brackets, indicating that the router we introduce is an object, and in front of Koa introduced is actually a class (so it is capitalized ~).

POST request is processed

router.get()处理的是HTTP的GET请求,但是除了GET请求,我们还经常会碰到POST请求(比如在注册一个用户啊,或者新增一篇推文的时候),这就需要用到router.post()的方法。不过,post请求的内容,通常作为request的body进行发送,而Node.js和koa都不具备解析这个body的功能,所以,这里我们就要用到另一个非常有用的middleware: koa-bodyparser

大专栏   Node.js Web开发(二)pt">
      
      
1
2
3
4
5
6
7
      
      
const bodyParser = require( 'koa-bodyparser');
app.use(bodyParser());
app.use(router.routes());
...

现在,我们就可以处理POST的请求了!

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
      
      
router.get( '/', async (ctx, next) => {
ctx.response.body = `<h1>Index Page</h1>
<form action="/signin" method="post">
<p>Name: <input name="name" value="snow"></p>
<p>Password: <input type="password" name="password"></p>
<p><input type="submit" value="submit"></p>
</form>`;
});
router.post( '/signin', async(ctx, next) => {
var
name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log( `login with name: {$name} and password: {$password}...`);
if (name === 'snow' && password === '117'){
ctx.response.body = `<h1>Welcome, {$name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed.</h1>
<p><a href="/">Try again</a></p>`;
}
});

注意这里的name和password的写法,如果不存在的话,默认为 ‘’,也不会报错的。

Guess you like

Origin www.cnblogs.com/liuzhongrong/p/12000002.html