nodejs获取服务器数据到页面
const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa(); const router = new Router(); 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 handler onerror(app) // middlewares app.use(bodyparser()) .use(json()) .use(logger()) .use(require('koa-static')(__dirname + '/public')) .use(views(path.join(__dirname, '/views'), { options: { settings: { views: path.join(__dirname, 'views') } }, map: { 'html': 'nunjucks' }, extension: 'html' })) .use(router.routes()) .use(router.allowedMethods()) // x-response-time app.use(async function(ctx, next) { const start = new Date(); await next(); const ms = new Date() - start; ctx.set('X-Response-Time', `${ms}ms`); }); // logger app.use(async function(ctx, next) { const start = new Date(); await next(); const ms = new Date() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}`); }); app.on('error', (err, ctx) => log.error('server error', err, ctx) ); router.get('/', async(ctx, next) => { var bd = "bd"; // 从服务器获取数据 bd = await getData(); ctx.state = { title: 'Koa2', name: bd } // 发送到页面 return await ctx.render('index', ctx.state) }) //获取服务器数据 async function getData(){ return new Promise((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: '小明-list' } await ctx.render('b', ctx.state) }) app.listen(3000); console.log('listen http://localhost:3000');