KoaJS教程

Koa.js 请求对象

一个 Koa 请求对象是在 node 的 vanilla 请求对象之上的抽象,提供了对日常 HTTP 服务器开发有用的附加功能。 Koa 请求对象嵌入在上下文对象中, this。每当我们收到请求时,让我们注销请求对象。
var koa = require('koa');
var router = require('koa-router');
var app = koa();
var _ = router();
_.get('/hello', getMessage);
function *getMessage(){
   console.log(this.request);
   this.body = 'Your request has been logged.';
}
app.use(_.routes());
app.listen(3000);
当您运行此代码并导航到 https://localhost:3000/hello 时,您将收到以下响应。
请求对象
在您的控制台上,您将注销请求对象。
{ 
   method: 'GET',
   url: '/hello/',
   header: 
   { 
      host: 'localhost:3000',
      connection: 'keep-alive',
      'upgrade-insecure-requests': '1',
      'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) 
         AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
      accept: 'text/html,application/xhtml+xml,
         application/xml;q = 0.9,image/webp,*/*;q = 0.8',
      dnt: '1',
      'accept-encoding': 'gzip, deflate, sdch',
      'accept-language': 'en-US,en;q = 0.8' 
   }
}
我们可以使用此对象访问请求的许多有用属性。让我们看一些例子。

request.header

提供所有请求标头。

请求方法

提供请求方法(GET、POST等)

请求.href

提供完整的请求 URL。

请求路径

提供请求的路径。没有查询字符串和基本网址。

request.query

`
给出解析的查询字符串。例如,如果我们将其记录在诸如 https://localhost:3000/hello/?name=Ayush&age=20&country=India 之类的请求上,那么我们将获得以下对象。
{
   name: 'Ayush',
   age: '20',
   country: 'India'
}

request.accepts(type)

此函数根据请求的资源是否接受给定的请求类型返回 true 或 false。
您可以在 Request 的文档中阅读有关请求对象的更多信息。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4