Web全栈开发案例教程(AI辅助版)-实验大纲实验六:简易新闻系统的实现_第1页
Web全栈开发案例教程(AI辅助版)-实验大纲实验六:简易新闻系统的实现_第2页
Web全栈开发案例教程(AI辅助版)-实验大纲实验六:简易新闻系统的实现_第3页
Web全栈开发案例教程(AI辅助版)-实验大纲实验六:简易新闻系统的实现_第4页
Web全栈开发案例教程(AI辅助版)-实验大纲实验六:简易新闻系统的实现_第5页
已阅读5页,还剩12页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

实验六:用4种框架分别实现简易新闻系统导读:以一个简易新闻系统的开发实例,分别用4种框架实现。实现零基础入门Node.js、微信小程序、Vue.js、React等前端框架技术。要实现的新闻系统首页和内容页如图所示:图1网页版新闻系统列表页图2网页版新闻系统详情页图3微信小程序端新闻列表页 图4微信小程序新闻详情页1.Node.js+Express思路:在Node.js的路由处理函数中渲染模板,并将数据发送给模板。在模板文件中绑定数据。·routes/index.js文件的代码varexpress=require('express');varrouter=express.Router();constconn=require('../db');router.get('/',function(req,res,next){//处理首页的路由,发送两个栏目框的数据给模板varquery='select*fromnewsorderbyiddesclimit6'; conn.query(query,function(err,rows,fields){ vartitle=rows; varquery2="select*fromnewswhereBigClassName='学生工作'orderbyiddesclimit6"; conn.query(query2,function(err,rows,fields){ vartitle2=rows; res.render('lm',{title:title,title2:title2,formatD:formatD}); }); });});router.get('/show',function(req,res,next){//处理内容页的路由,发送一条记录的数据给模板 vararticleID=req.query.id; //获取首页传来的文章ID varqry='SELECT*FROMnewsWHEREID='+conn.escape(articleID); conn.query(qry,function(err,rows,fields){ varqry2='UPDATEnewsSEThits=hits+1WHEREID='+conn.escape(articleID); vararticle=rows[0]; console.log(article); conn.query(qry2,function(err,rows,fields){ time=formatD(time); res.render('show',{ article:article }); }); });});module.exports=router;·views/lm.ejs文件的代码<divclass="news"><divclass="title"><h2>新闻动态</h2><spanclass="more"><ahref="more.htm">更多>></a></span></div><ulclass="list_one"><%for(leti=0;i<title.length;i++){%> <li><ahref="show?id=<%=title[i].ID%>"><%=title[i].title%></a><b><%=formatD(title[i].infotime)%></b></li><%}%> </ul></div><divclass="news"><divclass="title"><h2><%=title2[0].BigClassName%></h2><spanclass="more"><ahref="more.htm">更多>></a></span></div><ulclass="list_one"><%for(leti=0;i<title2.length;i++){%> <li><ahref="show?id=<%=title2[i].ID%>"><%=ellipsee(title2[i].title,18)%></a><b><%=formatD(title2[i].infotime)%></b></li><%}%> </ul></div>·views/show.ejs文件的代码<bodystyle="width:700px;margin:20pxauto;"> <h1><%=article.title%></h1> <divstyle="border:1pxdashed#666;height:1.8em;text-align:center"> 发布者:<%=article.user%>发布时间:<%=time%>点击次数<%=article.hits%> </div> <divstyle="font-size:16px;color:#999"><%-article.content%></div> </body>2.微信小程序实现简易新闻系统微信小程序、Vue.js和React访问Node.js后端输出的数据,都可以实现前后端分离的架构。在前后端分离架构下,后端的Node.js程序完全一样,其思路是输出json数据给前端。1.后端程序将routes/index.js文件的代码修改如下:router.get('/',function(req,res,next){ varquery='select*fromnewsorderbyiddesclimit6'; conn.query(query,function(err,rows,fields){ vartitle=rows; varquery2="select*fromnewswhereBigClassName='学生工作'orderbyiddesclimit6"; conn.query(query2,function(err,rows,fields){ vartitle2=rows; vartitall=[...title,...title2]; res.send(titall); }); });});router.get('/show',function(req,res,next){ letid=req.query.id; varquery='select*fromnewswhereid='+id; conn.query(query,function(err,rows,fields){ vartitle=rows[0]; console.log(rows); res.send(title); });});2.微信小程序端的代码index/index.js文件Page({ onLoad:function(options){ this.getList() }, getList:function(){ var_self=this wx.request({ url:'http://localhost:3000',//请求的Node.js端网址 methods:'GET', success:function(res){ console.log(res.data); //用于测试 _self.setData({ title:res.data.splice(0,6), //将返回的数组前半赋值给title title2:res.data.splice(0,6) //将返回的数组后半赋值给title2 }); } }) }, seeDetail:function(e){ //跳转到新闻详情页 varId=e.currentTarget.id;wx.navigateTo({url:'../show/show?Id='+Id,//url:'../show/show/'+Id,})}})index/index.wxml文件<viewclass="news"><viewclass="title"><view>新闻动态</view><textclass="more"><ahref="more.htm">更多>></a></text></view><viewclass="list_one"> <viewid="{{title[i].ID}}"wx:for="{{title}}"wx:for-index="i"wx:key="id"bindtap='seeDetail'><ahref="show?id={{title[i].ID}}">{{title[i].title}}</a><b>{{title[i].infotime}}</b></view></view></view><viewclass="news"><viewclass="title"><view>{{title2[0].BigClassName}}</view><textclass="more"><ahref="list?type={{title2[0].BigClassName}}">更多>></a></text></view><viewclass="list_one"> <viewid="{{title2[i].ID}}"wx:for="{{title2}}"wx:for-index="i"wx:key="id"bindtap='seeDetail'><ahref="show?id={{title2[i].ID}}">{{title2[i].title}}</a><b>{{title2[i].infotime}}</b></view> </view></view>show/show.js文件varIdconst{stripHtml}=require('../func/func.js');Page({data:{},onLoad:function(options){Id=options.Idconsole.log(options)this.loadDetail()},loadDetail:function(){if(Id!=""){var_self=this;wx.request({url:'http://localhost:3000/show?id='+Id, //发送Id给后端程序method:'GET',success:function(res){vartitle=res.data;title.content=stripHtml(title.content);_self.setData({title:title});}})}},})show/show.wxml文件<viewclass="header">{{title.title}}</view><viewclass="content">{{title.content}}</view>3.Vue前端实现新闻系统本例采用Vue构建模式,将HTML代码写在<template>中,CSS代码写在<style>中,JavaScript代码写在exportdefault{}中。1.新闻列表页的实现:App.vue<script> importaxiosfrom'axios'; exportdefault{ created(){ //页面载入时执行 this.getbooks(); }, data(){ return{ title:[], title2:[] } }, methods:{ getbooks(){ varself=this; axios.get('http://localhost:3000',{ params:{ } }).then(function(response){ self.title=response.data.splice(0,6); self.title2=response.data.splice(0,6); //console.log(response.status); //console.log(self.title); }).catch(function(error){ console.log('请求失败:'+error.status+','+error.statusText); }); }, } }</script><template> <divclass="news"> <divclass="title"> <h2>新闻动态</h2> <spanclass="more"><ahref="more.htm">更多>></a></span> </div> <ulclass="list_one"> <liv-for="(item,index)intitle":key="index"> <a:href="'show?id='+item.ID">{{item.title}}</a><b>{{time}}</b> </li> </ul> </div> <divclass="news"> <divclass="title"> <h2>新闻动态</h2> <spanclass="more"><ahref="more.htm">更多>></a></span> </div> <ulclass="list_one"> <liv-for="(item,index)intitle2":key="index"> <a:href="'show?id='+item.ID">{{item.title}}</a><b>{{time}}</b> </li> </ul> </div></template><style> .news{ width:480px; margin-left:20px; } .title{ height:40px; line-height:40px; /*设置标题栏高度并使内容垂直居中*/ border-bottom:2pxsolid#025483; padding-bottom:2px; display:flex; justify-content:space-between; } .titleh2{ height:40px; /*标题左浮动*/ font-size:22px; color:#000; border-bottom:4pxsolid#900; padding-right:40px; margin:0; /*去掉h2标记的默认上下边界*/ } .title.more{ display:block; height:22px; padding-right:10px; } /*“更多”右边保留一点间距*/ .morea{ font-size:14px; text-decoration:none; color:#666; } .list_one{ min-height:245px; /*设置内容区域的最小高度*/ margin-top:10px; /*设置第一条新闻上面的间隙*/ } .list_oneli{ line-height:36px; height:36px; /*垂直居中*/ color:#999; font-size:18px; padding-left:6px; text-overflow:ellipsis; /*文本溢出则裁切*/ white-space:nowrap; /*强制不换行*/ overflow:hidden; /*溢出内容隐藏*/ display:flex; justify-content:space-between; } .list_oneli::before{ display:inline-block; content:""; width:0; height:0; border:6pxsolidtransparent; border-left-color:#c13432; margin-top:14px; } .list_onelia{ flex-grow:1; text-overflow:ellipsis; /*文本溢出则裁切*/ white-space:nowrap; /*强制不换行*/ overflow:hidden; /*溢出内容隐藏*/ } .list_onelib{ font-weight:normal; width:80px; text-align:right; }</style>提示:要修改Vue项目的端口号,修改项目目录下以下2处即可:在package.json中,把"dev":"vite--port5173",在vite.config.js中,添加:exportdefaultdefineConfig({plugins:[vue()],server:{port:5173//将端口改为5173}})2.添加路由实现新闻列表页和新闻详情页。(1)src/App.vue<template><divid="app"><router-view></router-view></div></template>(2)router/index.jsimport{createRouter,createWebHistory}from'vue-router'constroutes=[{path:'/',name:'NewsList',component:()=>import('../views/NewsList.vue')},{path:'/news/:id',name:'NewsDetail',component:()=>import('../views/NewsDetail.vue')}]constrouter=createRouter({history:createWebHistory(),routes})exportdefaultrouter(3)views/NewsList.vue<template><divclass="news"><divclass="title"><h2>新闻动态</h2><spanclass="more"><ahref="more.htm">更多>></a></span></div><ulclass="list_one"><liv-for="(item,index)intitle":key="index"><router-link:to="'/news/'+item.ID">{{item.title}}</router-link><b>{{time}}</b></li></ul></div><divclass="news"><divclass="title"><h2>{{title2[0].title}}</h2><spanclass="more"><ahref="more.htm">更多>></a></span></div><ulclass="list_one"><liv-for="(item,index)intitle2":key="index"><router-link:to="'/news/'+item.ID">{{item.title}}</router-link><b>{{time}}</b></li></ul></div></template>其他代码与上一节中App.vue的代码完全相同。特别注意:虽然<router-link>标签中传递ID是采用的路由参数形式,但Vue会截获该路由,委托给axios传递参数给后端程序,而axios传递id参数时会采用url参数的形式,因此后端程序必须使用req.query.id方式获取参数。特别注意:(4)views/NewsList.vue<script>importaxiosfrom'axios';exportdefault{created(){this.getNewsDetail();},data(){return{news:null,isLoading:true}},methods:{getNewsDetail(){this.isLoading=true;varself=this;axios.get('http://localhost:3000/news',{params:{id:this.$route.params.id}}).then(function(response){self.news=response.data;self.isLoading=false;}).catch(function(error){console.log('请求失败:'+error.status+','+error.statusText);self.isLoading=false;});}}}</script><template><divclass="detail"><router-linkto="/"class="back-link">←返回新闻列表</router-link><divv-if="isLoading"class="loading">加载中...</div><divv-else-if="news"class="detail-content"><h1class="detail-title">{{news.title}}</h1><divclass="detail-meta"><spanclass="detail-time">{{time}}</span></div><divclass="detail-body"v-html="news.content"></div></div><divv-elseclass="not-found">新闻不存在</div></div></template><stylescoped>.detail{width:80%;margin:20pxauto;padding:20px;background:#fff;box-shadow:02px10pxrgba(0,0,0,0.1);}.back-link{display:inline-block;padding:8px16px;background:#025483;color:#fff;border-radius:4px;font-size:14px;margin-bottom:20px;text-decoration:none;}.back-link:hover{background:#013a5c;}.loading{text-align:center;padding:50px;color:#999;}.detail-content{line-height:1.8;}.detail-title{font-size:28px;color:#000;margin-bottom:20px;padding-bottom:10px;border-bottom:1pxsolid#eee;}.detail-meta{color:#999;font-size:14px;margin-bottom:20px;}.detail-body{font-size:16px;color:#333;}.detail-bodyimg{max-width:100%;height:auto;margin:10px0;}.detail-bodyp{margin-bottom:1em;}.not-found{text-align:center;padding:50px;color:#999;font-size:18px;}</style>4.React实现新闻系统前端本例中列表页对应NewsList()组件,新闻详情页对应NewsDetail组件。在根组件App中定义到这两个组件的路由。src/App.js代码import'./style.css';importReact,{useState,useEffect}from'react';import{Routes,Route,Link}from'react-router-dom';importaxiosfrom'axios';importNewsDetailfrom'./components/NewsDetail';functionNewsList(){const[data,setData]=useState([]);const[data2,setData2]=useState([]);useEffect(()=>{constfetchData=async()=>{constresult=awaitaxios('http://localhost:3000');console.log(result.data);setData(result.data.splice(0,6)); setData2(result.data.splice(0,6));};fetchData();},[]);return(<><divclassName="news"><divclassName="title"><h2>新闻动态</h2><spanclassName="more"><ahref="more.htm">更多>></a></span></div><ulclassName="list_one">{data.map(item=>(<likey={item.ID}><Linkto={`/show/${item.ID}`}>{item.title}</Link><b>{time}</b></li>))}</ul> </div> <divclassName="news"> <divclassName="title"> <h2>新闻动态</h2> <spanclassName="more"><ahref="more.htm">更多>></a></span> </div> <ulclassName="list_one">{data2.map(item=>(<likey={item.ID}><Linkto={`/show/${item.ID}`}>{it

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论