Create project (creating a complete website using KOA one)

Before developing a website, we first prepare the background development environment. Here we choose nodejs, and then use the koa framework as the WEB framework.
1. The first step is to create a project. We use VSODE for development. First, create a folder, and then execute yarn init in this folder to initialize the project. The main purpose is to generate a package.json to define the project name. Author and dependencies, etc., the efficiency is as follows, the role of package.json is to manage some information of this project.

yarn init
question name (zizch): zizch
question version (1.0.0):
question description: zizch
question repository url:
question author: Kang_Chen
question license (MIT):
question private:
success Saved package.json
Done in 159.75s.
PS D:\chen\nodejs\zizch> yarn add
yarn add v1.22.19
error Missing list of packages to add to your project.
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
PS D:\chen\nodejs\zizch> yarn add koa2

insert image description here
2. Add the dependent module of the koa2 framework, yarn add koa2, after the installation is successful, use yarn list koa2 to see if the installation is successful

PS D:\chen\nodejs\zizch> yarn list koa2
yarn list v1.22.19
warning Filtering by arguments is deprecated. Please use the pattern option instead.
└─ koa2@2.0.0-alpha.7
Done in 0.11s.

3. Start creating the app.js entry file. It is also relatively simple here, just introduce koa and create a Koa instance, and then start the service. If the server can return the result normally, you need to use middleware. app.use, ctx is a parameter that encapsulates the request and response objects , we can return the result hello koa through ctx.body

const Koa = require('koa') // 引入koa
const app = new Koa() // 声明实例
// 编写中间件
app.use((ctx)=> {
    
    
    // ctx: content http请求上下文
    ctx.body = 'hello koa'
  })

//启动服务
app.listen(3000,()=>{
    
    
    console.log('server is running at http://127.0.0.1:3000');
});

Then we can enter http://localhost:3000/ in the browser to visit.

insert image description here

Guess you like

Origin blog.csdn.net/weixin_36557877/article/details/129354694