use-server
v0.4.9
Published
A light-weight, promise-based and middleware-driven web framework
Downloads
1,153
Maintainers
Readme
A light-weight, promise-based and middleware-driven web framework
Features
- Use promise-based middlewares
- Better error handle, you can use
app.on('error', cb)
ortry/catch
withasync/await
in middleware - Easily use express middlewares(see Migrate from express)
- The core is light-weight, all functionalities are driven by use-* middlewares, like
use-router
,use-cache
; - Support forward functionality:
req.forward('/new/url')
Example
const createApp = require('use-server');
const app = createApp();
app.use(async (req, resp, next)=>{
console.log('1');
await next();
console.log('3');
})
app.use(async (req, resp, next)=>{
try{
let user = await User.queryDb();
resp.end(user.name);
}catch(e){
resp.statusCode = 500;
resp.end(e.message)
}
console.log('2');
})
app.listen(8080)
Migrate from express
Currently only support express middleware operations, like express.Router
and express.use|all|get|post|...()
const useServer = require('use-server');
const app = useServer()
//express middlewares
app.express.get('/a', (req, resp, next)=>{
console.log(req.url);
next()
})
app.express.use(require('compression')())
app.express.use(require('body-parser').json())
API
require('use-server')()
: create an app server.app.use(...middlewares)
: add middlewares. A middleware is a function like(req, resp, next)=>{}
.app.listen()
: same as nodeserver.listen()
function.app.on('error', cb)
: catch uncaught error in middlewaresreq.basePath
: request context, used in router.req.forward(url)
: forward the request to another url.
Middleware plugins
- use-router: Router
License
Licensed under MIT
Copyright (c) 2017 kiliwalk