Const KOA = require (' Koa '); Const Router= Require (' Koa-router '); Const app=NewKoa (); const router=NewRouter (); Const views= Require (' Koa-views '); Const JSON= Require (' Koa-json '); Const OnError= Require (' Koa-onerror '); Const Bodyparser= Require (' Koa-bodyparser '); Const path= Require (' path '); Const logger= Require (' Koa-logger '); Const request= Require (' request '));//Error Handleronerror (APP)//MiddlewaresApp.use (Bodyparser ()). Use (JSON ()). Use ( logger ()). Use (Require (' Koa-static ') (__dirname + '/public ')). Use (Path.join (__dirname,'/views '{ options: {settings: {views:path.join (__dirname,' Views ')}}, Map: {' HTML ': ' Nunjucks '}, Extension:' HTML '}). Use (Router.routes ()). Use (Router.allowedmethods () )//X-response-timeApp.use (Asyncfunction(CTX, next) {Const start=NewDate (); await next (); Const MS=NewDate ()-start; Ctx.set (' X-response-time ', ' ${ms}ms ');});//LoggerApp.use (Asyncfunction(CTX, next) {Const start=NewDate (); await next (); Const MS=NewDate ()-start; Console.log (' ${ctx.method} ${ctx.url}-${ms} '); App.on (' Error ', (err, CTX) =Log.error (' Server error ', err, CTX)); Router.get ('/', async (CTX, next) = { varBD = "BD"; //getting data from the serverBD=await GetData (); Ctx.state={title:' Koa2 ', NAME:BD}//Send To Page returnAwait Ctx.render (' index ', Ctx.state)})//Get Server DataAsyncfunctionGetData () {return NewPromise ((resolve,reject) ={Request ("Https://www.baidu.com", (error,response,body) ={ if(Error) {Reject ("Error") }Else{Resolve ("Thank You") (//body} )})}router.get ('/b ', async (CTX, next) ={ctx.state={title:' Koa2 ', Name:' Xiaoming-list '} await Ctx.render (' B ', Ctx.state)}) App.listen (3000); Console.log (' Listen http://localhost:3000 ');
Nodejs get Server data to page