ikcamp / koa-node.js-web-fe-development Goto Github PK
View Code? Open in Web Editor NEW《Koa与Node.js开发实战》第1-8章代码
Home Page: https://www.ikcamp.cn
《Koa与Node.js开发实战》第1-8章代码
Home Page: https://www.ikcamp.cn
这本书里面的视频链接失效了吗,还是怎么,打不开,链接如 https://camp.qianduan.group/koa2/2/1/6
错误的地方
nock('http://test.com')
.get('/test1')
request.post('test.com/test1')
正确的地方
nock('http://test.com')
.post('/test1')
request.post('http://test.com/test1')
错误的代码
const should = require('chai').should();
const nock = require('nock');
//const request = require('request');
const request = require('superagent');
const foo = 'bar';
describe('request', () => {
beforeEach(() => {
// Nock代码
nock('http://test.com')
.get('/test1')
.delay(200)
.reply(200, { foo: 'bar' });
}),
it('core', (done) => {
request.post('test.com/test1').end((err, res) => {
res.text.should.equal('{"foo":"bar"}');
res.body.foo.should.equal('bar');
done();
});
})
});
正确的代码
const should = require('chai').should();
const nock = require('nock');
//const request = require('request');
const request = require('superagent');
const foo = 'bar';
describe('request', () => {
beforeEach(() => {
// Nock代码
nock('http://www.test.com')
.post('/test1')
.delay(200)
.reply(200, { foo: 'bar' });
});
it('core', (done) => {
request.post(`http://www.test.com/test1`).end((err, res) => {
res.text.should.equal('{"foo":"bar"}');
res.body.foo.should.equal('bar');
done(); // 显式调用这个函数,通知 Mocha 测试结束.
});
});
});
ctx.body 有错
错误代码
router.post('/customer', async (ctx, err) => {
const customer = ctx.body
await createCustomer(customer)
ctx.type = jsonMIME
ctx.body = {
status: 0
}
})
正确代码
router.post('/customer', async (ctx, err) => {
const customer = ctx.request.body
await createCustomer(customer)
ctx.type = jsonMIME
ctx.body = {
status: 0
}
})
发送数据的代码
curl --data-ascii "id=12434&name='yaoming'&sex='man'&address='Shanghai Road'&email='[email protected]'&phone='12323132123'&country='China'&city='Shanghai'" http://127.0.0.1:3000/customer
就知道了.
1、26行fullAddress的get方法中是应该是:getDataValue 而不是 getDateValue
2、40行 sequelize.STRING 写法有误应该是:Sequelize.STRING
如上代码会导致同步数据的时候出现:Error: Unrecognized data type for field city
3、另外db/index.js中的第6行 fulladdress 和model定义中的 fullAddress 写的不一致
const koa = require('koa');
const app = new koa();
const hostname = '127.0.0.1';
const port = 3000;
app.use(async ctx=>{
await asyncFunction1(params);
await asyncFunction2(params);
await asyncFunction3(params);
ctx.body='Hello World!';
});
app.listen(port);
console.log(`Server(Koa2) running at http://${hostname}:${port}/`);
访问 http://127.0.0.1:3000/ 报错
ReferenceError: asyncFunction1 is not defined
at app.use (d:\Code\nodejs_test\koa2_002\index_koa2.js:6:5)
at dispatch (d:\Code\nodejs_test\koa2_002\node_modules\koa-compose\index.js:42:32)
at d:\Code\nodejs_test\koa2_002\node_modules\koa-compose\index.js:34:12
at Application.handleRequest (d:\Code\nodejs_test\koa2_002\node_modules\koa\lib\application.js:151:12)
at Server.handleRequest (d:\Code\nodejs_test\koa2_002\node_modules\koa\lib\application.js:133:19)
at Server.emit (events.js:193:13)
at parserOnIncoming (_http_server.js:680:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:113:17)
application.js:190
ReferenceError: asyncFunction1 is not defined
at app.use (d:\Code\nodejs_test\koa2_002\index_koa2.js:6:5)
at dispatch (d:\Code\nodejs_test\koa2_002\node_modules\koa-compose\index.js:42:32)
at d:\Code\nodejs_test\koa2_002\node_modules\koa-compose\index.js:34:12
at Application.handleRequest (d:\Code\nodejs_test\koa2_002\node_modules\koa\lib\application.js:151:12)
at Server.handleRequest (d:\Code\nodejs_test\koa2_002\node_modules\koa\lib\application.js:133:19)
at Server.emit (events.js:193:13)
at parserOnIncoming (_http_server.js:680:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:113:17)
var koa= require('koa');
var app = new koa();
var hostname = '127.0.0.1';
var port = 3000;
app.use(function*(){
yield asyncFunction1(params);
yield asyncFunction2(params);
yield asyncFunction3(params);
this.body='Hello World!'
});
var server = app.listen(port);
console.log(`Server(Koa) running at http://${hostname}:${port}/`);
运行后 访问 http://127.0.0.1:3000/ 报错报错
ReferenceError: asyncFunction1 is not defined
at Object.<anonymous> (d:\Code\nodejs_test\koa2_002\index_koa.js:6:5)
at Generator.next (<anonymous>)
at onFulfilled (d:\Code\nodejs_test\koa2_002\node_modules\co\index.js:65:19)
at d:\Code\nodejs_test\koa2_002\node_modules\co\index.js:54:5
at new Promise (<anonymous>)
at Object.co (d:\Code\nodejs_test\koa2_002\node_modules\co\index.js:50:10)
at converted (d:\Code\nodejs_test\koa2_002\node_modules\koa-convert\index.js:17:15)
at dispatch (d:\Code\nodejs_test\koa2_002\node_modules\koa-compose\index.js:42:32)
at d:\Code\nodejs_test\koa2_002\node_modules\koa-compose\index.js:34:12
at Application.handleRequest (d:\Code\nodejs_test\koa2_002\node_modules\koa\lib\application.js:151:12)
application.js:190
错误的curl POST命令:
curl http://127.0.0.1:3000/api/login\?username\=test
正确的curl POST命令:
curl --data "username=test" "http://127.0.0.1:3000/api/login"
用户名连接数据库,弄了很久才解决
书中代码有问题
async function connect() {
await mongoose.connect('mongodb://localhost/course', {
user: 'adminUser',
pass: 'adminPass'
});
}
报错1
(node:812) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
MongoDB报错2
2019-06-15T22:41:24.853+0800 I ACCESS [conn3] SASL SCRAM-SHA-1 authentication failed for adminUser on course from client 127.0.0.1:53152 ; UserNotFound: Could not find user adminUser@course
改成
async function connect() {
await mongoose.connect('mongodb://localhost/course?authSource=admin', {
useNewUrlParser: true,
user: 'adminUser',
pass: 'adminPass'
});
}
就可以了.
《koa 与 nodejs》一书中第六章数据库6.3.3节代码不全,看得云里雾里的,上github才发现原来漏掉了代码中重要的部分。
1.文件的开头应该说明这个是哪个文件。现在的只能靠猜。。。
2.该节model/course.js书上的源码少了一大块。最后courseSchema连导出的对象中weekday字段都被省略掉了。导致下文中index.js难以读懂。
感谢ikcamp编写此书。
错误代码
router.post('/course', async context => {
context.request.type = JSON_MIME;
await addCourse(context.body);
context.type = JSON_MIME;
context.body = { status: 0 };
});
正确代码
router.post('/course', async context => {
context.request.type = JSON_MIME;
await addCourse(context.request.body);
context.type = JSON_MIME;
context.body = { status: 0 };
});
curl命令post数据的代码
curl --data "name='CV001'&weekday=1&startTime.time=10&startTime.hour=11&startTime.minute=20&endTime.time=11&endTime.hour=12&endTime.minute=30" "http://127.0.0.1:3000/course"
应该把
id: Sequelize.UUID,
改成
id: {
type: Sequelize.UUID,
primaryKey: true
}
把
title: Sequelize.STRING,
改成
type: Sequelize.STRING,
var express = require('express');
var app=express();
var hostname = '127.0.0.1';
var port = 3000;
app.get('/',function(req,res){
asyncFunction1(params, function(){
asyncFunction2(params, function(){
asyncFunction3(params, function(){
res.send('Hello World!');
});
});
});
});
var server = app.listen(3000);
console.log(`Server running at http://${hostname}:${port}/`);
运行后,访问 http://127.0.0.1:3000/ 报错
C:\Program Files\nodejs\node.exe' --nolazy --debug-brk=49936 index_express.js
Debugger listening on [::]:49936
Server running at http://127.0.0.1:3000/
ReferenceError: asyncFunction1 is not defined
at d:\Code\nodejs_test\koa2_002\index_express.js:6:5
at Layer.handle [as handle_request] (d:\Code\nodejs_test\koa2_002\node_modules\express\lib\router\layer.js:95:5)
at next (d:\Code\nodejs_test\koa2_002\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (d:\Code\nodejs_test\koa2_002\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (d:\Code\nodejs_test\koa2_002\node_modules\express\lib\router\layer.js:95:5)
at d:\Code\nodejs_test\koa2_002\node_modules\express\lib\router\index.js:281:22
at Function.process_params (d:\Code\nodejs_test\koa2_002\node_modules\express\lib\router\index.js:335:12)
at next (d:\Code\nodejs_test\koa2_002\node_modules\express\lib\router\index.js:275:10)
at expressInit (d:\Code\nodejs_test\koa2_002\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (d:\Code\nodejs_test\koa2_002\node_modules\express\lib\router\layer.js:95:5)
97页
重写controller/home.js中的login方法,代码如下:
login: async(ctx, next) => {
await ctx.render('home/login', {
btnName: 'GoGoGo'
})
}
应该改成
重写controller/home.js中的user方法,代码如下:
user: async(ctx, next) => {
await ctx.render('home/login', {
btnName: 'GoGoGo'
})
}
书中和前面的例子是用user啊。
或者应该改书前面的代码,用login,这样要合理点。
差static,views下的文件啊,例子能给一个么?
const koa = require('koa');
const app = new koa();
const views = require('koa-views');
const path = require('path');
const static = require('koa-static');
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');
const router = new Router();
const process = require('process');
const hostname = '127.0.0.1';
const port = 3000;
app.use(views(__dirname + '/views', { // 加载模板引擎
map: { html: 'ejs' }
}));
app.use(staic(path.join(__dirname, '/static')));
router.get('/', (ctx, next) => {
await ctx.render('index');
});
router.post('/', (ctx, next) => {
// 当POST请求时,中间件koa-bodyparser解析POST表单里的数据
let postData = ctx.request.body;
ctx.body = postData;
})
app.use(bodyParser()) // 加载koa-bodyparser中间件
.use(router.routes()) // 加载koa-router中间件
.use(router.allowedMethods()); //对异常状态码的处理
app.listen(port, () => {
console.log(`Version: ${process.version}`);
console.log(
`Server(Koa2)(koa-static,koa-views) running at http://${hostname}:${port}`
);
});
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.