主要通过node实现搭建服务,实现数据交互。
插件安装:npm install axios koa koa-router koa-static koa-views -S
初始化node项目:
npm init
文件目录结构:
main.js文件:
项目入口,主要配置项目的静态资源、html模板、路由和node服务的开启
import Koa from 'koa'
import koaStatic from 'koa-static'
import views from 'koa-views'
import router from './koaRouter.js'
import path from 'path'
let app = new Koa();
// 当前项目的路径
const __dirname = path.resolve();
// 引入静态目录(简单来说可以文件中可以引入的js、图片等这类静态资源,如本项目index.html文件中引入了../js/index.js)
app.use(koaStatic(__dirname));
// 使用html格式
app.use(views(__dirname+"/views"), {
extension: "html"
});
// 引入路由,并使用
app.use(router.routes());
// node项目启动
app.listen(8887,'127.0.0.9', ()=>{
console.log('127.0.0.9:8887')
});
koaRouter.js文件:
配置需要显示的页面,如首页index,详情页detail。
import router from './api/api.js'
// 重定向,如果页面地址是/ ,自动跳转到/index
router.get("/",async ctx=>{
ctx.redirect('/index');
});
// 首页
router.get("/index",async ctx=>{
await ctx.render("./index.html");//渲染views下的index.html
});
// 详情页
router.get("/detail",async ctx=>{
await ctx.render("./detail.html");
});
export default router;
api/api.js文件:
后端接口:新闻列表和详情
import Router from 'koa-router'
import fs from "fs";
import path from 'path'
let routerApi = new Router();
const __dirname = path.resolve();
/**
* des: 获取新闻列表接口
* 接口配置:
* {
* contentType: 请求方式 application/x-www-form-urlencoded
* method: 请求类型 get
* }
* 默认参数:
* {
* page: 1, 页数
* pageSize: 5 每页条数
* }
* 返回参数:
* {
* pageSize: 5,
* page: 1,
* list: [{...},{...}...],
* count: *
* }
*/
routerApi.get("/list",ctx => {
let page = ctx.query.page || 1;
let pageSize = ctx.query.pageSize || 5;
let newsList = JSON.parse(fs.readFileSync(__dirname + "/assets/data.json").toString());
let count = 0 || newsList.length;
ctx.body = {
page,
pageSize,
count,
list: newsList.slice(page * pageSize - pageSize, page * pageSize)
}
});
/**
* des: 获取新闻详情页
* 接口配置:
* {
* contentType: 请求方式 application/x-www-form-urlencoded
* method: 请求类型 get
* }
* 默认参数:
* {
* id: *
* }
* 返回参数:
* {
* list: {...}
* }
*/
routerApi.get("/newsDetail",ctx => {
let id = ctx.query.id;
let newsList = JSON.parse(fs.readFileSync(__dirname + "/assets/data.json").toString());
let list = undefined;
for(let i = 0; i < newsList.length; i++){
if(newsList[i].id == id){
list = newsList[i];
break;
}
}
ctx.body = {
list
}
});
export default routerApi;
views/index.html文件:
新闻首页
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首页title>
<style>
body,html{
margin: 0;
padding: 0;
width:100%;
height:100%;
}
.wrap{
width:600px;
margin: 40px auto;
border:1px solid #ccc;
padding: 50px;
}
a{
text-decoration: none;
color: rgba(0,0,0,.65);
}
#pagination{
text-align: center;
}
#pagination a{
height: 32px;
margin-right: 8px;
display:inline-flex;
justify-content: center;
align-items: center;
vertical-align: middle;
min-width: 32px;
list-style: none;
background-color: #fff;
border: 1px solid #d9d9d9;
border-radius: 4px;
outline: 0;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
padding: 0 6px;
transition: none;
}
.active{
font-weight: 500!important;
color: #1890ff!important;
background: #fff!important;
border-color: #1890ff!important;
}
ul{
margin: 0;
padding-bottom:50px ;
}
ul li{
list-style-type: none;
padding-bottom: 5px;
border-bottom: 1px solid #ccc;
}
ul li h3{
font-size: 16px;
margin-bottom: 5px;
}
.info{
font-size: 14px;
text-align: right;
}
style>
head>
<body>
<div class="wrap">
<ul id="news-list">ul>
<div id="pagination">div>
div>
body>
<script src="../js/axios.js">script>
<script src="../js/index.js">script>
html>
js/index.js文件:
新闻首页js代码
let page = 1;// 当前页
let pageSize = 5;// 每页页数
// 获取dom元素
let dom = document.getElementById("news-list");
let paginationDom = document.getElementById("pagination");
// 一共多少页
let allPage = undefined;
// 判断是否为第一次执行
let init = true;
getNewsList();
// 获取新闻列表
function getNewsList(){
axios.get('/list',{
params: {
page,
pageSize
},
}).then(function (response) {
const data = response.data;
// 新闻列表
let str = '';
data.list.forEach(element => {
str += `
${ element.id }">${ element.title }
${ element.author }
| ${ element.addTime }
`;
});
dom.innerHTML = str;
// 分页器
// 如果是第一执行,添加分页器元素,否则只修改点击的某一页样式
if(init){
init = false;
let paginationStr = `
`;
allPage = Math.ceil(data.count / data.pageSize);
for(let i = 1; i <= allPage; i++){
if(data.page == i){
paginationStr += `
${ i }')">${ i }
`;
}else{
paginationStr += `
${ i }')">${ i }
`;
}
}
paginationStr += `
`;
paginationDom.innerHTML = paginationStr;
}else{
// 处理分页器的当前页
document.getElementsByClassName("active")[0]?.classList.remove('active');
paginationDom.children[data.page].classList.add("active");
}
}).catch(function (error) {
// handle error
console.log(error);
});
}
// 点击分页器,刷新列表
function paginationClick(sort){
switch(sort){
case 'prev':
page--;
if(page <= 0){
page = 1;
return;
}
break;
case 'next':
page++;
if(page > allPage){
page = allPage;
return;
}
break;
default:
page = +sort;
}
getNewsList();
}
views/detail.html文件:
新闻列表点击后进入的详情页面
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>详情页title>
<style>
body,html{
margin: 0;
padding: 0;
width:100%;
height:100%;
}
.wrap{
width:600px;
margin: 40px auto;
text-align: center;
border:1px solid #ccc;
padding: 50px;
}
.info{
font-size: 14px;
text-align: right;
display: flex;
justify-content: end;
color: rgb(119, 114, 114);
}
.content{
line-height: 20px;
margin-top: 10px;
text-align: left;
text-indent: 2rem;
}
.button{
text-align: right;
cursor: pointer;
color: #1890ff;
}
.button::after{
color: #40a9ff;
}
style>
head>
<body>
<div class="wrap">div>
body>
<script src="../js/axios.js">script>
<script src="../js/detail.js">script>
html>
js/detail.js文件:
新闻详情页js代码
// 获取dom元素
let dom = document.getElementsByClassName("wrap")[0];
getDetail();
// 获取详情页
function getDetail(){
// 请求接口
axios.get('/newsDetail',{
params: {
id: GetQuery('id'),
},
}).then(function (response) {
let data = response.data.list;
let str = `
${ data.title }
${ data.author } |
${ data.addTime }
${ data.content }
`;
dom.
innerHTML = str;
}).catch(function (error) {
// handle error
console.log(error);
});
}
// 获取URL后缀
function GetQuery(key){
let after = window.location.search;
after = after.substr(1) || window.location.hash.split('?')[1];
if (after) {
const reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`);
const r = after.match(reg);
if (r != null) {
return (r[2]);
}
return null;
}
return null;
};
assets/data.json文件
数据
[
{
"addTime": "2019-6-18",
"author":"小红",
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"content": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"id": 2,
"addTime": "2021-1-9",
"author":"小明",
"title": "qui est esse",
"content": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"addTime": "2018-10-20",
"author":"春华",
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"content": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
{
"addTime": "2021-10-20",
"author":"张三",
"id": 4,
"title": "eum et est occaecati",
"content": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
},
{
"addTime": "2021-1-8",
"author":"李四",
"id": 5,
"title": "nesciunt quas odio",
"content": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
},
{
"addTime": "2020-5-18",
"author":"王五",
"id": 6,
"title": "dolorem eum magni eos aperiam quia",
"content": "ut aspernatur corporis harum nihil quis provident sequi\nmollitia nobis aliquid molestiae\nperspiciatis et ea nemo ab reprehenderit accusantium quas\nvoluptate dolores velit et doloremque molestiae"
},
{
"addTime": "2021-1-20",
"author":"小红",
"id": 7,
"title": "magnam facilis autem",
"content": "dolore placeat quibusdam ea quo vitae\nmagni quis enim qui quis quo nemo aut saepe\nquidem repellat excepturi ut quia\nsunt ut sequi eos ea sed quas"
},
{
"addTime": "2021-7-16",
"author":"小张",
"id": 8,
"title": "dolorem dolore est ipsam",
"content": "dignissimos aperiam dolorem qui eum\nfacilis quibusdam animi sint suscipit qui sint possimus cum\nquaerat magni maiores excepturi\nipsam ut commodi dolor voluptatum modi aut vitae"
},
{
"addTime": "2018-11-22",
"author":"路飞",
"id": 9,
"title": "nesciunt iure omnis dolorem tempora et accusantium",
"content": "consectetur animi nesciunt iure dolore\nenim quia ad\nveniam autem ut quam aut nobis\net est aut quod aut provident voluptas autem voluptas"
},
{
"addTime": "2019-4-11",
"author":"带土",
"id": 10,
"title": "optio molestias id quia eum",
"content": "quo et expedita modi cum officia vel magni\ndoloribus qui repudiandae\nvero nisi sit\nquos veniam quod sed accusamus veritatis error"
},
{
"addTime": "2021-10-1",
"author":"卡卡西",
"id": 11,
"title": "et ea vero quia laudantium autem",
"content": "delectus reiciendis molestiae occaecati non minima eveniet qui voluptatibus\naccusamus in eum beatae sit\nvel qui neque voluptates ut commodi qui incidunt\nut animi commodi"
},
{
"addTime": "2021-10-20",
"author":"罗宾",
"id": 12,
"title": "in quibusdam tempore odit est dolorem",
"content": "itaque id aut magnam\npraesentium quia et ea odit et ea voluptas et\nsapiente quia nihil amet occaecati quia id voluptatem\nincidunt ea est distinctio odio"
},
{
"addTime": "2021-10-20",
"author":"王五",
"id": 13,
"title": "dolorum ut in voluptas mollitia et saepe quo animi",
"content": "aut dicta possimus sint mollitia voluptas commodi quo doloremque\niste corrupti reiciendis voluptatem eius rerum\nsit cumque quod eligendi laborum minima\nperferendis recusandae assumenda consectetur porro architecto ipsum ipsam"
},
{
"addTime": "2021-1-1",
"author":"张三",
"id": 14,
"title": "voluptatem eligendi optio",
"content": "fuga et accusamus dolorum perferendis illo voluptas\nnon doloremque neque facere\nad qui dolorum molestiae beatae\nsed aut voluptas totam sit illum"
},
{
"addTime": "2020-12-25",
"author":"张红",
"id": 15,
"title": "eveniet quod temporibus",
"content": "reprehenderit quos placeat\nvelit minima officia dolores impedit repudiandae molestiae nam\nvoluptas recusandae quis delectus\nofficiis harum fugiat vitae"
},
{
"addTime": "2021-3-15",
"author":"杰克",
"id": 16,
"title": "sint suscipit perspiciatis velit dolorum rerum ipsa laboriosam odio",
"content": "suscipit nam nisi quo aperiam aut\nasperiores eos fugit maiores voluptatibus quia\nvoluptatem quis ullam qui in alias quia est\nconsequatur magni mollitia accusamus ea nisi voluptate dicta"
},
{
"addTime": "2010-6-17",
"author":"秀才",
"id": 17,
"title": "fugit voluptas sed molestias voluptatem provident",
"content": "eos voluptas et aut odit natus earum\naspernatur fuga molestiae ullam\ndeserunt ratione qui eos\nqui nihil ratione nemo velit ut aut id quo"
},
{
"addTime": "2010-2-17",
"author":"蓦然回首",
"id": 18,
"title": "voluptate et itaque vero tempora molestiae",
"content": "eveniet quo quis\nlaborum totam consequatur non dolor\nut et est repudiandae\nest voluptatem vel debitis et magnam"
},
{
"addTime": "2020-2-2",
"author":"菠萝吹雪",
"id": 19,
"title": "adipisci placeat illum aut reiciendis qui",
"content": "illum quis cupiditate provident sit magnam\nea sed aut omnis\nveniam maiores ullam consequatur atque\nadipisci quo iste expedita sit quos voluptas"
},
{
"addTime": "2021-10-20",
"author":"张舞",
"id": 20,
"title": "doloribus ad provident suscipit at",
"content": "qui consequuntur ducimus possimus quisquam amet similique\nsuscipit porro ipsam amet\neos veritatis officiis exercitationem vel fugit aut necessitatibus totam\nomnis rerum consequatur expedita quidem cumque explicabo"
},
{
"addTime": "2021-10-20",
"author":"张舞",
"id": 21,
"title": "doloribus ad provident suscipit at",
"content": "qui consequuntur ducimus possimus quisquam amet similique\nsuscipit porro ipsam amet\neos veritatis officiis exercitationem vel fugit aut necessitatibus totam\nomnis rerum consequatur expedita quidem cumque explicabo"
}
]
js/axios.js文件
自己网上拷贝
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
提示:
项目使用的是module,所以必须在package.json 添加"type": "module",
另外项目扩展:node mysql pug 实现新闻后管
今天又是令人emo的周一了!!!Σ(  ̄д ̄;) !!!