koajs / examples Goto Github PK
View Code? Open in Web Editor NEWExample Koa apps
Example Koa apps
所有的请求都指向首页 其他页面都进不去了
app.use(function* (next){
try {
yield* next;
} catch (err) {
if (401 == err.status) {
this.status = 401;
this.body = 'cant haz that';
} else {
throw err;
}
}
});
==>
app.use(function *(next){
try {
yield next;
} catch (err) {
if (401 == err.status) {
this.status = 401;
this.set('WWW-Authenticate', 'Basic');
this.body = 'cant haz that';
} else {
throw err;
}
}
});
bash: make: command not found
Can I add these links to this repo?
Your examples link to a 404 github page
there is a "undefined" when I run the compose/app.js
undefined / - 6
undefined / - 1
undefined /aaaa - 0
I think that the code 'this' will be modified to 'ctx' in the 'logger()' function.
While the Koa docs specifically say that setting ctx.respond
to false
is not a supported pattern, it is necessary for embedding a Koa application into a large Express application -- the use case is incrementally moving routes from Express/Connect style to Koa. I'm curious if you're open to adding an example here of how to do that, because it can be a little tricky and there are several pitfalls. As a reference example I put together this repo: https://github.com/bttmly/koa-within-express
But I think it could be useful here for others looking for an Express to Koa migration path!
migrated from koajs/koa#101
node upload/app.js
open http://localhost:3000
choose a file
click upload
TypeError: Cannot read property 'file' of undefined
In the example, custom 404 works only if no response from any downstream middleware.
Нowever, if any downstream middleware throws an exception, pageNotFound() middleware don't works (default 404 page will be sent).
See my pull request with a test (currently broken): https://github.com/koajs/examples/pull/82/files
I tried the 404 example , but I found some problems
I tried to make some requests with different custom headers(text/plain and application/json), but the I found that the responses were not what I expected:
➜ ~ http --print=Hhb localhost:3000 Content-Type:text/html
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: text/html
Host: localhost:3000
User-Agent: HTTPie/0.9.9
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 21
Content-Type: text/html; charset=utf-8
Date: Wed, 03 May 2017 16:48:50 GMT
<p>Page Not Found</p>
➜ ~ http --print=Hhb localhost:3000 Content-Type:application/json
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json
Host: localhost:3000
User-Agent: HTTPie/0.9.9
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 21
Content-Type: text/html; charset=utf-8
Date: Wed, 03 May 2017 16:50:05 GMT
<p>Page Not Found</p>
➜ ~ http --print=Hhb localhost:3000 Content-Type:multipart/form-data
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: multipart/form-data
Host: localhost:3000
User-Agent: HTTPie/0.9.9
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 21
Content-Type: text/html; charset=utf-8
Date: Wed, 03 May 2017 16:50:35 GMT
<p>Page Not Found</p>
No matter how I set up what kind of Content-Type,The results are always same.
Is this a bug or my use is not correct?
[2:54 pm, 03/08/2021] 🍫🍫: 1. Given values on the next page, write a function that returns an array of strings in the
following format
["Norah | AAA-6818 | 564.67","Norah | AAA-4671 | 138971.19"]
2. Execute your function and output the results as an array in console log for the following
scenarios:
A) filtered by Norah with all account types (ROT, IRA, AAA)
B) filtered by account type sorted by balance ascending
C) filtered by Alyx with IRA account type; sorted by balance descending
D) filtered by All users; sorted by balance ascending
users = [
{
id: "1",
name: "Norah"
},
{
id: "2",
name: "Alyx"
}
];
accounts = [
{
account: "IRA-4679",
user: "1",
balance: "5175.36"
},
{
account: "AAA-3571",
user: "1",
balance: "3896342.08"
},
{
account: "AAA-4671",
user: "1",
balance: "138971.19"
},
{
account: "ROT-1687",
user: "2",
balance: "2686.00"
},
{
account: "AAA-7894",
user: "2",
balance: "68761.32"
},
{
account: "IRA-6818",
user: "2",
balance: "564.67"
},
{
account: "IRA-6819",
user: "2",
balance: "4564.67"
}
};
I know the version of koa
used in the examples differs from the version I'm using following along with the examples (2.2.0
vs. 2.5.2
), but wanted to raise a fundamental difference in the ctx
object for extracting files from the request:
app.js
in the examples has the following:
const files = ctx.request.body.files || {};
In version 2.5.2
, this has to be set as follows:
const files = ctx.request.files || {};
Pretty sure it's a difference between versions, but figured I'd raise the issue in the event that someone else has troubles.
While studying koajs capabilities i made some REST API by using latest koa.
The question are examples, in this repo, should consist of next version yet or until official release only koa1?
About my code https://github.com/DoumanAsh/lazy-http-can
This repo consist of simple REST service that allows you to test HTTP requests.
There are several things:
ctx.response
might be cool :) https://github.com/DoumanAsh/lazy-http-can/blob/master/server/router.js#L44-L45Both packages are currently unmaintained.
Koa-router has already been forked by us and is available as @koa/router
.
Swig has been forked too and undergoes some further development as swig-templates
.
These two forks aren't under to much development either and more or less stale but using @koa/router
gives us a bit more control and swig-templates
already fixed some bugs and has more up-to-date dependencies (which npm audit
will tell you).
I haven't bothered looking into the other packages but these two I think should get updated...
Maybe adding coding styles check for this repo could make the example codes coherence.
Just some suggestion.
See also:
https://github.com/koajs/koa/blob/v2.x/.eslintrc.yml
https://github.com/feross/standard
The "hello-world" runs out of the box and is really easy.
The "api-boilerplate" example needs some extra files and doesn't run work.
Hello, I am trying to use the properties parameter with ctx.throw but I do not see the object added anywhere in the response. For example, if part of a request message is missing, I want to do something like the following:
if (!username) {
return ctx.throw(400, 'Invalid request message', {
validationErrors: {
username: 'Username cannot be null',
},
});
}
When I try to do a console.log of the response, I see the status and message set properly but I do not see the validationErrors object in the response. Any suggestions on this are appreciated.
PULL REQUESTS WELCOME!!!
The included upload example throws an error that part.pipe
is not defined.
If I understand well, the vhost example no longer works with version 3.0.0 of koa-compose.
Could it be updated?
I take it koa-compose 3.0.0 cannot be used with Koa 1.x.x.
The error example only details how to handle this.throw
and throw new
. Where as the koajs application *respond(next)
generator handles 404 by
// status body
var status = this.status = this.status || 404;
...
if (null == body) {
this.type = 'text';
body = http.STATUS_CODES[status];
}
I would need to use a second generator to repeat similar logic to the *respond(next)
generator to enforce json as well. Any suggestions how to handle this elegantly / use the same try / catch
generator as per the example?
Using master from koajs/examples with node v0.12.0 to run the stream-server-side-events example program, I had a couple problems:
I had to add if (!module.parent) app.listen(3000);
as the final line of app.js
I got the following error when I connected to http://localhost:3000
richs-mbp-10715:stream-server-side-events richb$ node --harmony app.js
RangeError: msecs must be a non-negative finite number
at Object.exports.enroll (timers.js:160:11)
at Socket.setTimeout (net.js:329:12)
at IncomingMessage.setTimeout (_http_incoming.js:89:15)
at Object.<anonymous> (/Users/richb/github/KoaJSExamples/stream-server-side-events/app.js:9:12)
at GeneratorFunctionPrototype.next (native)
at Object.respond (/Users/richb/node_modules/koa/lib/application.js:180:10)
at GeneratorFunctionPrototype.next (native)
at Object.<anonymous> (/Users/richb/node_modules/koa/node_modules/koa-compose/index.js:29:12)
at GeneratorFunctionPrototype.next (native)
at onFulfilled (/Users/richb/node_modules/co/index.js:61:19)
^C
If I comment out the line setTimeout(Infinity)
line, I get the following when I hit the server:
richs-mbp-10715:stream-server-side-events richb$ node --harmony app.js
events.js:85
throw er; // Unhandled 'error' event
^
TypeError: Invalid non-string/buffer chunk
at chunkInvalid (_stream_readable.js:384:10)
at readableAddChunk (_stream_readable.js:140:12)
at Subscription.Readable.push (_stream_readable.js:126:10)
at Subscription._read (/Users/richb/github/KoaJSExamples/stream-server-side-events/db.js:30:30)
at Subscription.Readable.read (_stream_readable.js:341:10)
at resume_ (_stream_readable.js:725:12)
at _stream_readable.js:717:7
at process._tickCallback (node.js:355:11)
the need swig in blog app.
Stream never stop.
Please create an example similar to https://github.com/visionmedia/express/tree/master/examples/vhost as it would be invaluable :)
I'v installed the dependence, but , I can't run the test.js file like this:
node .\base-auth\test.js
It shows ReferenceError: describe is not defined.
can they be runing successfully in your computer?
I use vscode 1.17.1
Os: windows
node is the latest version 8.6.0
See koajs/logger#8
I'm mostly interested in the stream-view and SSE examples. Thanks.
https://github.com/koajs/examples/blob/master/stream-view/view.js
I can see how to use koa application in express using koa.callback() but how do I mount an existing express app in koa?
Thank you
Adding an example for how to do websockets would be grand, I'll PR one once I figure it out myself 😅
Hi,
I cloned the whole repo and ran npm install
, then nav into blog/ ran 'node index.js', and got this error. Can you help with it? thank you. 😄
I'm using node v5.4.0 and linuxmint 3.16.0-38-generic.
Error: Invalid cache option true found. Expected "memory" or { get: function (key) { ... }, set: function (key, value) { ... } }.
at validateOptions (/home/sabrina/sa/koa-examples/node_modules/swig/lib/swig.js:113:15)
try to log every push on server - you'll see than on a client there is not a stream - there is long waiting for whole result as usual
In my samples the first push occurs in 2 ms but on the client TTFB is equal sum of times in the request - so there is no real stream unfortunately
in this example. it can only handle one connection at once. The other connections are waitting for the previous one finish up to start streaming process
i think most people are going to just view this on github vs. actually cloning it, so i think we should move most of the non-technical and philosophical explanations to a readme in each directory. opinions?
I have an Express app that already starts its own http server. How can I mount a koa app on top of this existing server, so that it shares the same port? Similar to how you would mount subapps in Express
Would I include the koa app as an Express middlware? Do I still use app.callback()
for that?
Hi,
I'm trying to upload files using the code from example. But it's not working.
In the controller I wrote the code
var parse = require('co-busboy');
var fs = require('fs');
var path = require('path');
var parts = parse(this);
var part;
while (part = yield parts) {
var stream = fs.createWriteStream('/tmp/' + part.filename);
part.pipe(stream);
console.log('uploading %s -> %s', part.filename, stream.path);
}
But when I upload images in the console I only get new uploading location. But on new location images are not saving.
Any Solution?
Thanks in Advance,
Nixon
The stream-server-side-events examples located here https://github.com/koajs/examples/tree/master/stream-server-side-events
I hope this makes sense but I am trying to see how I will be able to update my application with koa with no restart.
basically, all started request should keep flowing as they began ; all new request should flow to the new version of the app.
in pseudo code it would be something like
var rolling = [ myapp ]
var app = koa();
app.use(function *() {
var m = compose(rolling[0])
return yield m.call(this, next);
});
... somewhere an event does a
rolling.unshift(newapp);
now if I have a koa-livecount middleware like
function livecounter() {
var count = 0;
return function livecount*(next) {
count +=1;
yield next;
count -=1;
}
}
with
myapp.use(livecounter());
I could know when myapp has finished handling requests.
(is this really correct when throw is used somewhere below ? is there a way to know when there are zero processing requests downstream for an app or a middleware ?)
when i know that myapp is not used anymore I can pop it out of the rolling array.
do you think something like this could work and could we try to setup an example for this ?
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.