1.1.5 • Published 3 years ago
node-cross v1.1.5
node-cross
Node-cross is a tiny but complete http server framework for nodejs. The features include:
- Application context
- Middlewares like Koa.js
- Built-in static service
- Built-in routing service
- Built-in template engine
Installation
npm i node-crossGet Started
const Cross = require("node-cross");
new Cross()
.static("/assets")
.engine({
root: "template",
imports: { globalName: "cross" }
})
.on("error", (err, ctx) => {
console.error(err);
ctx.body = {
status: ctx.status,
message: ctx.body
};
})
.use(async (ctx, next) => {
ctx.custom = "xxxx";
await next();
})
.get("/", async ctx => {
console.log(ctx.query);
console.log(ctx.params)
})
.listen();API Reference
Methods
app.engine(options)Enable template engine with options{ root, imports }.app.static(path)Serve static resources with the givenpath.app.on("error", function)Custom unified error handling.app.use(function)Add a middleware like koa.js.app.get(path, [tmpl,] function)Add dynamic route includingpost,put,deleteand other standard request methods, it will auto-render template iftmplparameter exists.app.listen([port])Create and start an application server on the specified port.app.callback()Return a request handler for node's native http server.
Context
Properties
ctx.paramsGet params in route path, wildcard supportsctx.queryGet params in query stringctx.methodGet request methodctx.pathGet request pathctx.urlGet request full hrefctx.protocolGet request protocolctx.hostGet request hostctx.hostnameGet request hostnamectx.originGet request originctx.headersGet headers objectctx.cookiesGet cookies objectctx.statusGet response status codectx.bodyGet response bodyctx.requestGet native requestctx.responseGet native responsectx.status=Set response status codectx.body=Set response body
Methods
ctx.get(name)Get request headers by namectx.set(name, value)Set response headersctx.cookie(name, value[, options])Set cookiesasync ctx.json()Get request body in jsonasync ctx.text()Get request body in textasync ctx.buffer()Get request body in bufferctx.redirect(url[, status])Redirect url with status default 301ctx.view(path, data)Render template file, only if engine enabled.ctx.render(path, data)Render template text, only if engine enabled.ctx.throw(message, status)Throw an error with status code
Route Syntax
/staticstatic route/*Wildcard route, it will returnwildcardvariable inctx.params/:user/:user?/:user(\\d+)