hello,JS:12-02搭建服务器(上)

一、如何获取数据(涉及开发流程)

1、获取数据

前端部分写了一个ajax,请求需要发送到服务器的接口上,服务器如果是不存在,直接报错,且无法后续测试,对于数据的处理、渲染无从谈起。接口如何运作起来,有数据返回,接口:后端开发

2、网站的开发流程

(1)需求(前端、后端)
(2)前后端工作

  • 前端:写页面(html、css样式,js交互)
  • 后端:提供数据

(3)如做一个天气预报的页面网站:对前端页面功能的分解,数据需要什么?(前端主导?两者主导?)

  • 与后端协商:天气预报的数据接口:根据城市获取当天的天气;根据城市、日期获取某天的天气(接口url、传递的参数(城市?经纬度、ip、中英文)、返回数据格式(结构?字段?))
  • 前端:模拟假数据(与后端协商后)

(4)前后端开发完成,进行真实数据的测试、优化

3、搭建服务器

终端,启用静态服务器:

1
$ http-server

打开相应地址:我的是,http://127.0.0.1:8080 (你的端口号不一定和我一样,不要纠结)

点开文件,简单功能开发时,把对应功能的接口放在html对应目录下,新建一个文件(json数据文件,即对应功能的数据),上传至githubpages或其他静态页面服务器上,其功能存在,继续进行功能的交互,就能获取相应功能数据。

二、mock数据方法

1、方法1、线上githubpagesmock数据

(1)github创建一个项目:wxq393/wangyiyunmusic
(2)分别创建文件
A、html文件——home.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//home.html
<!doctype html>
<head>
<style>
.cate .item {
border: 1px solid #ccc;
line-height: 20px;
padding: 0 10px;
}
</style>
</head>
<body>
<header></header>
<main>
<div class="cate"></div>
</main>

<script>
var xhr = new XMLHttpRequest()
xhr.open('GET', '/wangyiyunmusic/cate.json', true)
xhr.send()
xhr.onload = function(){
render(JSON.parse(xhr.responseText))
console.log(JSON.parse(xhr.responseText))
}

function render(cateData){
for(var i = 0; i < cateData.length; i++){
var node = document.createElement('div')
node.classList.add('item')
node.innerText = cateData[i]
document.querySelector('.cate').appendChild(node)
}
}
</script>
</body>

如图:熟悉一下dom的语法

B、json文件——cate.json(注意路径)

1
2
//cate.json
["90后", "80后", "清晨", "工作"]

C、直接githubpage去mock数据,如图:

2、方法2 使用 easymock mock数据

A、进入http://easy-mock.com/
创建url域名——创建接口——编辑json数据——更新、预览:即能看到返回的数据

1
2
3
4
5
6
7
8
9
10
/*json数据编写:*/
{
"success": true,
"data": [
"80后",
"90后",
"00后",
"清晨喝咖啡"
]
}

返回数据另一种方法:点击主页面生成的url,使用终端测试,也能返回相应数据

1
$ curl  url地址

如图:

B、(继续)尝试在本地测试
使用项目文件,添加请求数据的文件(文件名:1.html),代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var xhr = new XMLHttpRequest()
//所请求的数据url地址
xhr.open('GET','https://easy-mock.com/mock/5b51c4919ce5fe26a0a3043d/getType',true)
xhr.send()

xhr.addEventListener('load',function(){
console.log(xhr.status)
if((xhr.status >= 200 && xhr.status <300) ||xhr.status ===304){
var data = xhr.responseText
console.log(data)

}else{
console.log('error')
}

})

xhr.onerror = function(){
console.log('error')
}

</script>
</body>
</html>

右键启动该项目的终端服务器:

1
$ http-server

相应打开对应项目文件的url地址——检查——显示数据格式文件(定义好数据),说明所请求的数据已返回:

3、方法3 使用 http://rapapi.org/org/index.do

4、方法4 使用 server-mock

-------------本文结束感谢您的阅读-------------