koa2 服务端渲染web开发,怎么处理浏览器事件触发的数据交互?
一般怎么处理,我能想到的是在node服务端做一些接口,如下图:
routes/news.js
const router = require('koa-router')({
prefix: '/news'
})
const config = require('../config')
const controllers = require('../controllers')
router.get('/', async (ctx, next) => {
const { companyNews, industryNews } = await controllers.news.getList(ctx, next)
await ctx.render('news', {
header: {
title: '新闻中心',
javascript: config.javascript.concat('/js/jqpaginator.min.js', '/js/frontNewsCenter.js'),
style: config.style.concat('/css/frontNewsCenter.css'),
},
newBanner: {
imgSrc: '/images/news/banner.png',
},
tabNav: {
items: [{
cn: '公司新闻',
en: 'Company news',
}, {
cn: '行业咨询',
en: 'Industry information',
}],
},
companyNews: companyNews,
industryNews: industryNews,
})
})
router.get('/getList', controllers.news.getList)
module.exports = router
controllers/news.js
const { getCompanyNewsList, getIndustryInfoList } = require('../config').service
const axios = require('axios')
async function getList (ctx, next) {
const page = ctx.query.page || '1' // page
const size = ctx.query.size || '10' // size
const role = ctx.query.role || 'news' // role
let code = -1
let data = []
let companyNews = []
let industryNews = []
if (role === 'news') {
await axios.get(getCompanyNewsList, {
params: {
page: page,
size: size
}
})
.then(res => {
if (res.data.code === '2000') {
code = 0
data = res.data.obj
companyNews = res.data.obj.records
}
})
}
if (role === 'industry') {
await axios.get(getIndustryInfoList, {
params: {
page: page,
size: size
}
})
.then(res => {
if (res.data.code === '2000') {
code = 0
data = res.data.obj
industryNews = res.data.obj.records
}
})
}
ctx.state.code = code
ctx.state.data = data
return {
companyNews,
industryNews,
}
}
module.exports = {
getList
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
restful服务, ctx.body等于ctx.response.body