ts构建koa_如何使用Koa构建“ Hello World”应用程序

ts构建koa

介绍 (Introduction)

Express is one of the most popular Node.js frameworks out there. Koa is a new web framework created by the team behind Express. It aims to be a modern and more minimalist version of Express. Some of its characteristics are its support and reliance on new JavaScript features such as generators and async/await. Koa also does not ship with any middleware though it can be extended using custom and existing plugins.

Express是目前最流行的Node.js框架之一。 Koa是由Express背后的团队创建的新的Web框架。 它旨在成为Express的现代且更加简约的版本。 它的一些特征是它对新JavaScript功能(例如generatorsasync / await)的支持和依赖。 Koa也没有附带任何中间件,尽管可以使用自定义插件和现有插件进行扩展。

By following this article, you will learn more about the Koa framework and build an app to get familiar with its functionality and philosophy.

通过阅读本文,您将了解有关Koa框架的更多信息,并构建一个应用程序以熟悉其功能和理念。

先决条件 (Prerequisites)

To follow along with this tutorial, you would need the following installed:

要继续学习本教程,您需要安装以下软件:

You also need to have a working knowledge of JavaScript and ES6 syntax.

您还需要掌握JavaScript和ES6语法的使用知识。

设置和配置 (Setup and Configuration)

To begin, create a new directory for your project. This can be done by copying and running the command below in your terminal:

首先,为您的项目创建一个新目录。 这可以通过在终端中复制并运行以下命令来完成:

  • mkdir koala

    姆迪尔考拉

Note: You can give your project any name, but in this article we’ll be using koala as the project name and directory.

注意:您可以给项目指定任何名称,但是在本文中,我们将使用koala作为项目名称和目录。

At this point, you have created your project directory koala. Next, initialise your node project from inside the directory. You can do so by running the commands below:

至此,您已经创建了项目目录koala 。 接下来,从目录内部初始化您的节点项目。 您可以通过运行以下命令来这样做:

  • cd koala

    CD考拉
  • npm init koala

    npm初始化考拉

After running the npm init command, follow the prompts and fill in the details of your project. At the end of this, you will have a package.json file with the information you entered while prompted. Note that you can run npm init -y to create a package.json file with default values.

运行npm init命令后,按照提示进行操作并填写项目的详细信息。 最后,您将得到一个package.json文件,其中包含在提示时输入的信息。 请注意,您可以运行npm init -y创建具有默认值的package.json文件。

Next, run this command to install Koa:

接下来,运行以下命令以安装Koa:

  • npm install koa --save

    npm install koa-保存

Depending on the version of Node you have running you may not need to add the --save flag. This flag tells older versions of Node to add the installed library (in this case Koa) to the dependencies list in your package.json file. On newer Node versions, you can just run npm i koa to install Koa.

根据您所运行的Node的版本,您可能不需要添加--save标志。 此标志告诉Node的旧版本将已安装的库(在本例中为Koa)添加到package.json文件中的依赖项列表。 在较新的Node版本上,您只需运行npm i koa即可安装Koa。

创建Koa服务器 (Creating a Koa Server)

During the initialization of your project, you were prompted to enter the entry point of your application. In this article, you will use index.js which was the default value as your entry point.

在项目初始化期间,系统会提示您输入应用程序的入口点。 在本文中,您将使用作为默认值的index.js作为入口点。

First, create the index.js file. This can be done in several ways. For MacOS and Linux users, this can be done by running the below command in your terminal:

首先,创建index.js文件。 这可以通过几种方式来完成。 对于MacOS和Linux用户,这可以通过在终端中运行以下命令来完成:

  • touch index.js

    触摸index.js

Using your code/text editor of choice, open your project and copy the below snippet into the index.js file:

使用您选择的代码/文本编辑器,打开您的项目,并将以下代码段复制到index.js文件中:

// index.js

'use strict';

const koa = require('koa')
const app = new koa()

app.use(function *(){
  this.body = "Hello World !!!";
});

app.listen(1234)

In the snippet above, you created a koa application that runs on port 1234. You can run the application using the command:

在上面的代码段中,您创建了一个在端口1234上运行的koa应用程序。您可以使用以下命令运行该应用程序:

  • node index.js

    节点index.js

And visit the application on http://localhost:1234.

并访问http:// localhost:1234上的应用程序。

建立您的应用 (Building Out Your App)

As mentioned earlier, Koa.js does not ship with any contained middleware and unlike its predecessor, Express, it does not handle routing by default.

如前所述,Koa.js不附带任何包含的中间件,并且不同于其前身Express,它默认情况下不处理路由。

In order to implement routes in your Koa app, you will install a middleware library for routing in Koa, Koa Router. Install it by running:

为了在Koa应用程序中实现路由,您将安装用于在Koa中进行路由的中间件库,即Koa Router 。 通过运行以下命令进行安装:

  • npm install koa-router --save

    npm安装koa-router --save

To make use of the router in your application, amend your index.js file:

要在您的应用程序中使用路由器,请修改index.js文件:

// index.js

'use strict';
const koa = require('koa')
const koaRouter = require('koa-router')

const app = new koa()
const router = new koaRouter()

router.get('koala', '/', (ctx) => {
  ctx.body = "Welcome! To the Koala Book of Everything!"
})

app.use(router.routes())
  .use(router.allowedMethods())

app.listen(1234, () => console.log('running on port 1234'))

Above, you have defined a route on the base url of your application (http://localhost:1234) and registered this route to your Koa application.

上面,您已经在应用程序的基本URL( http:// localhost:1234 )上定义了一条路由,并将此路由注册到您的Koa应用程序。

For more information on route definition in Koa.js applications, visit the Koa Router library documentation here.

有关Koa.js应用程序中路由定义的更多信息,请访问此处的Koa Router库文档。

As already established, Koa comes as a minimalistic framework, therefore, to implement view rendering with a template engine you will have to install a middleware library. There are several libraries to choose from but in this article you will use koa-ejs.

正如已经确立的那样,Koa是一个简约的框架,因此,要使用模板引擎实现视图渲染,您将必须安装中间件库。 有几个库可供选择,但是在本文中,您将使用koa-ejs

To do so, first install the library using:

为此,首先使用以下命令安装库:

  • npm install koa-ejs --save

    npm install koa-ejs-保存

Next, amend your index.js file to register your templating with the snippet below:

接下来,修改index.js文件,使用以下代码段注册模板:

// index.js

'use strict';
const koa = require('koa')
const path = require('path')
const render = require('koa-ejs')
const koaRouter = require('koa-router')

const app = new koa()
const router = new koaRouter()

render(app, {
  root: path.join(__dirname, 'views'),
  layout: 'layout',
  viewExt: 'html',
  cache: false,
  debug: true
})

router.get('koala', '/', (ctx) => {
  ctx.body = "Welcome! To the Koala Book of Everything!"
})

app.use(router.routes())
  .use(router.allowedMethods())

app.listen(1234, () => console.log('running on port 1234'))

As seen above, in your template registering, you tell your application the root directory of your view files, the extension of the view files and the base view file (which other views extend).

如上所示,在模板注册中,您告诉应用程序视图文件的根目录,视图文件的扩展名和基本视图文件(其他视图所扩展的内容)。

Now that you have registered your template middleware, amend your route definition to render a template file:

现在您已经注册了模板中间件,修改路由定义以渲染模板文件:

// index.js

...

router.get('koala', '/', (ctx) => {
  let koala_attributes = [];
  koala_attributes.push({
    meta_name: 'Color',
    meta_value: 'Black and white'
  })
  koala_attributes.push({
    meta_name: 'Native Country',
    meta_value: 'Australia'
  })
  koala_attributes.push({
    meta_name: 'Animal Classification',
    meta_value: 'Mammal'
  })
  koala_attributes.push({
    meta_name: 'Life Span',
    meta_value: '13 - 18 years'
  })
  koala_attributes.push({
    meta_name: 'Are they bears?',
    meta_value: 'no!'
  })
  return ctx.render('index', {
    attributes: koala_attributes
  })
})

...

Above, your base route renders the index.html file found in the views directory. Your index.html file contains some basic HTML to display your koala attributes. See below:

在上方,您的基本路线将呈现在views目录中找到的index.html文件。 您的index.html文件包含一些基本HTML来显示您的考拉属性。 见下文:

<!-- views/index.html -->

<h2>Koala - a directory Koala of attributes</h2>
<ul class="list-group">
  <% attributes.forEach( function(attribute) { %>
    <li class="list-group-item">
      <%= attribute.meta_name %> - <%= attribute.meta_value %>
    </li>
  <% }); %>
</ul>

For more options with using the koa-ejs template middleware, view the library documentation here.

有关使用koa-ejs模板中间件的更多选项,请在此处查看库文档。

处理错误和响应 (Handling Errors and Responses)

Koa handles errors by defining an error middleware early in your entrypoint file. The error middleware must be defined early because only errors from middleware defined after the error middleware will be caught. Using your index.js file as an example, adjust it to include:

Koa通过在入口点文件中尽早定义错误中间件来处理错误。 错误中间件必须尽早定义,因为只会捕获在错误中间件之后定义的中间件中的错误。 以index.js文件为例,对其进行调整以包括:

// index.js

'use strict';
const koa = require('koa')
const render = require('koa-ejs')
const koaRouter = require('koa-router')

const app = new koa()
const router = new koaRouter()

app.use( async (ctx, next) => {
  try {
    await next()
  } catch(err) {
    console.log(err.status)
    ctx.status = err.status || 500;
    ctx.body = err.message;
  }
})

...

The above block catches any error thrown during the execution of your application. We’ll test this by throwing an error in the function body of the route you defined:

上面的块捕获了在应用程序执行期间引发的所有错误。 我们将通过在定义的路由的函数主体中引发错误来测试此问题:

// index.js

...

router.get('koala', '/', (ctx) => {
  ctx.throw('Test Error Message', 500)
}) 
...

The Koa response object is usually embedded in its context object. Using route definition, let’s show an example of setting responses:

Koa响应对象通常嵌入其上下文对象中。 使用路由定义,让我们展示一个设置响应的示例:

// index.js

'use strict';
const koa = require('koa')
const koaRouter = require('koa-router')

const app = new koa()
const router = new koaRouter()

app.use( async (ctx, next) => {
  try {
    await next()
  } catch(err) {
    console.log(err.status)
    ctx.status = err.status || 500;
    ctx.body = err.message;
  }
})

router.get('koala', '/', (ctx) => {
  ctx.status = 200
  ctx.body   = "Well this is the response body"
})

结论 (Conclusion)

In this article, you had a brief introduction to Koa and how to implement some common functionalities in a Koa project. Koa is a minimalist and flexible framework that can be extended to more functionality than this article has shown. Because of its futuristic similarity to Express, some have even described it as Express 5.0 in spirit.

在本文中,您简要介绍了Koa以及如何在Koa项目中实现一些常用功能。 Koa是一个极简且灵活的框架,可以扩展到比本文所示更多的功能。 由于它与Express的未来风格相似,有人甚至在本质上将其描述为Express 5.0。

The entire code from this article is available on Github, and the repository contains some additional concepts not treated here, as they are beyond the scope of the introduction.

Github上提供了本文的全部代码,并且该存储库包含一些其他概念,此处不作介绍,因为它们不在引言的范围之内。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-build-a-hello-world-application-with-koa

ts构建koa

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是基于 TypeScript、Koakoa-body 实现的文件上传代码示例: ```typescript import Koa from 'koa'; import koaBody from 'koa-body'; const app = new Koa(); // 设置上传文件的保存路径 const uploadDir = './uploads'; // koa-body 中间件配置 const koaBodyConfig = { multipart: true, // 启用文件上传 formidable: { uploadDir, // 文件保存路径 keepExtensions: true, // 保留文件扩展名 }, }; // 注册 koa-body 中间件 app.use(koaBody(koaBodyConfig)); app.use(async (ctx) => { // 判断是否为文件上传请求 if (ctx.request.files && ctx.request.files.file) { const { file } = ctx.request.files; // 输出上传文件信息 console.log(`Received file: ${file.name}`); console.log(`File size: ${file.size}`); console.log(`File path: ${file.path}`); ctx.body = 'File uploaded successfully.'; } else { ctx.body = 'Hello World!'; } }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); }); ``` 以上代码中,我们通过 `koa-body` 中间件启用了文件上传功能,并且设置了上传文件的保存路径。当接收到文件上传请求时,我们可以通过 `ctx.request.files.file` 获取上传的文件信息,然后对文件进行处理。如果不是文件上传请求,我们只是简单地返回了一个 "Hello World!" 字符串。 注意,我们在代码中没有对文件进行任何处理,只是输出了一些文件信息。在实际项目中,我们需要对上传的文件进行校验、存储和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值