Commit 1895ad7a authored by likely's avatar likely

第一课 - 启动web服务器

parent c9b24686
node_modules/
\ No newline at end of file
const koa = require('koa')
const app = new koa()
const router = require('./routes')
const koaBody = require('koa-body')
app.use(koaBody())
app.use(router.routes())
app.use(async ctx => {
ctx.body = 'hello world'
})
app.listen(3000)
\ No newline at end of file
const koaRouter = require('koa-router')
const router = new koaRouter({
prefix: '/api'
})
router.get('/books', async ctx => {
ctx.body = {
code: 0,
data: [
{
id: 1,
name: 'android',
author: 'sxx'
},
{
id: 2,
name: 'javascript',
author: 'likely'
},
{
id: 3,
name: 'ios',
author: 'sxx'
}
],
msg: null
}
})
router.del('/books/:id', async (ctx) => {
const id = ctx.params.id
if (!id){
ctx.body = {
code: 4001,
data: null,
msg: '缺少id参数'
}
} else {
ctx.body = {
code: 0,
data: null,
msg: `成功删除id为${id}的书籍`,
}
}
})
router.post('/books', async ({request, response}) => {
response.body = {
code: 0,
data: request.body,
msg: '成功新增一本书籍'
}
})
router.put('/books/:id', async (ctx) => {
const id = ctx.params.id
if (!id) {
ctx.body = {
code: 4001,
data: null,
msg: '缺少id参数'
}
} else {
ctx.body = {
code: 0,
data: null,
msg: '成功修改一本书籍'
}
}
})
module.exports = router
\ No newline at end of file
const http = require('http')
http.createServer(function(req, res) {
res.end('hello world')
}).listen(3000)
\ No newline at end of file
const http = require('http')
const url = require('url')
http.createServer(async function(req, res) {
const getBody = async () => {
return new Promise((resolve, reject) => {
let body = ''
req.on('data', function (data) {
body += data
})
req.on('end', function () {
resolve(body)
})
})
}
let body
if (method === 'POST') {
body = await getBody()
}
if (method === 'POST') {
res.end(body)
} else {
res.end('hello world')
}
}).listen(3000)
\ No newline at end of file
const http = require('http')
const url = require('url')
http.createServer(function(req, res) {
let reqUrl = req.url
const reqObj = url.parse(reqUrl)
const method = req.method
const pathName = reqObj.pathname
if (pathName === '/test' && method === 'GET'){
res.end('this is test page')
} else {
res.end('hello world')
}
}).listen(3000)
\ No newline at end of file
const koa = require('koa')
const app = new koa()
app.use(async ctx => {
ctx.body = 'hello world'
})
app.listen(3000)
\ No newline at end of file
const koa = require('koa')
const app = new koa()
const koaRouter = require('koa-router')
const router = new koaRouter({})
router.get('/test', async ctx => {
ctx.body = 'this is test page'
})
app.use(router.routes()).use(router.allowedMethods())
app.use(async ctx => {
ctx.body = 'hello world'
})
app.listen(3000)
\ No newline at end of file
{
"dependencies": {
"koa": "^2.7.0",
"koa-body": "^4.1.0",
"koa-router": "^7.4.0"
}
}
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment