可用教程地址:https://www.cnblogs.com/ruoqiang/p/6389935.html
官网地址:https://github.com/ruanyf/jstraining/tree/master/demos#rest-api
data.json文件
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
http://localhost:3000这个地址显示的是首页;
http://localhost:3000/posts 这个地址显示的是json文件里posts里的json数据
http://localhost:3000/comments 这个地址显示的是json文件里comments里的json数据
等于是一个json大文件,里面包含的一个个api接口,里面放路由
前面实现了获取文件,如何传到前台,如何修改文件,
koa的使用:---最简单的就可以打开端口,输出内容的了********************************************
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.response.body = 'Hello World22222';
};
app.use(main);
app.listen(3000);
实现最简单路由:***************************************************
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
if (ctx.request.path !== '/') {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
} else {
ctx.response.body = 'Hello World222';
}
};
app.use(main);
app.listen(3000); 当端口后面有其他的地址时,就会显示另外的内容。
使用route中间件的路由******************************************************************
const Koa = require('koa');
const app = new Koa();
const route = require('koa-route');
const about = ctx => {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page123</a>';
};
const main = ctx => {
ctx.response.body = 'Hello World456';
};
app.use(route.get('/', main));
app.use(route.get('/about', about));
app.listen(3000);
显示当前目录里的静态资源文件******************************************
const Koa = require('koa');
const app = new Koa();
const route = require('koa-route');
const path = require('path');
const serve = require('koa-static');
const main = serve(path.join(__dirname));
app.use(main);//这个可以显示当前目录里面的文件里的所有内容,js可以,html也可以
app.listen(3000);
路由的重新定向:这个路由完全无法打开,太快了看不到内容**********************************
const Koa = require('koa');
const app = new Koa();
const route = require('koa-route');
const redirect = ctx => {
ctx.response.redirect('/');
ctx.response.body = '<a href="/">Index Page</a>';
};
app.use(route.get('/redirect', redirect));
app.listen(3000);
中间件的执行顺序*****************************等于是next之前顺序执行,next之后的反序执行
const Koa = require('koa');
const app = new Koa();
const route = require('koa-route');
const one = (ctx, next) => {
console.log('>> one');
next();
console.log('<< one');
}
const two = (ctx, next) => {
console.log('>> two');
next();
console.log('<< two');
}
const three = (ctx, next) => {
console.log('>> three');
next();
console.log('<< three');
}
app.use(one);
app.use(two);
app.use(three);
app.listen(3000);
异步函数,虽然不知道怎么用的,但这个函数是可以正常运作的************************
const Koa = require('koa');
const app = new Koa();
const route = require('koa-route');
const fs = require('fs.promised');
const main = async function (ctx, next) {
ctx.response.type = 'html';
ctx.response.body = await fs.readFile('./index.html', 'utf8');
};
app.use(main);
app.listen(3000);