测试小白入门web开发之旅

298 阅读3分钟
「时光不负,创作不停,本文正在参加2021年终总结征文大赛

本人是一名深圳测试🐶,正在学习前端。 分享笔记一,如何入门web开发

一、讲解web开发流程

1、前后端的定义

Web开发就是开发网页程序,从开发简单的纯文本静态页面到复杂的基于Web的互联网应用程序,电子商务和社交网络服务。

代码运行在客户端,那些在客户端上的应用就是前端,通常指的就是我们的浏览器。

后端开发是运行在服务器上的代码,这部分的工作需要和数据库打交道,比如读写数据、读写文件、实现业务逻辑等。

二、怎么写一个页面html

1、页面的组成

html+css+js

HTML的基本结构:
<html>根控制标记(头)
         <head> 头控制标记(头)
               <title>标题</title> 标题标记
         </head> 头控制标记(尾)
         <body>网页显示区域(一般要实现的代码都在这里写)</body>
</html>根控制标记(尾)

eg:页面上有一个logo,怎么让它展示

html:加一个img标签

<img src="" id="picture" />

css:

#picture {
    width: 20px;
    height: 20px;
    border: 1px solid black;
    border-radius: 4px;
}

2、常见标签的使用

div -盒子 img -图片 a -链接 button - 按钮 input -输入框....

3、flex布局

www.runoob.com/w3cnote/fle…

三、怎么写js逻辑

1、标签绑定事件

eg:页面有一个按钮,怎么绑定点击事件跳到百度?

html:给button绑定点击事件

 <button class='login-button' onclick='handlejump()' title="欢迎进入到登录界面">立即体验</a> 

js:定义一个handlejump方法,打开一个新窗口,跳转到对应的链接

const定义一个常量target用来接收www.baidu.com

function handlejump() {
    const target = `https://www.baidu.com`                 
    window.open(target)
}

2、轮播图的渲染

  1. 放轮播图的容器

html:

  <div class="container">
</div>
  1. 轮播图的数据 js:
// // 背景图片列表
const backgroundList = [
 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimages2017.cnblogs.com%2Fnews%2F66372%2F201802%2F66372-20180208220802763-1908370397.png&refer=http%3A%2F%2Fimages2017.cnblogs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640189462&t=0efab59d145e8e37f599a785281705eb',
    `https://img0.baidu.com/it/u=3015107692,3301923892&fm=26&fmt=auto`,
    `https://img1.baidu.com/it/u=757606031,646429214&fm=26&fmt=auto`,
    `https://img1.baidu.com/it/u=3465066951,577846474&fm=26&fmt=auto`,
    `https://img2.baidu.com/it/u=64944061,1344734849&fm=26&fmt=auto`,
    `https://img1.baidu.com/it/u=2201558941,4109635095&fm=26&fmt=auto`,
    `https://img1.baidu.com/it/u=1322800825,931757870&fm=26&fmt=auto`
]
  1. 怎么数据渲染到容器里面
  • 轮播图的切换按钮 (html+css)
  • 写切换逻辑

点击⬅️,图片切到上一张

点击➡️,图片切到下一张

点到第1张或者最后一张时,相对的🔘点不动

// 当前背景图索引(记住当前位置)

let currentBgIndex = 0

//实现点击时切换框左右切换

function handletoggleBg(type) {

console.log(type);

const leftToggle = document.getElementById('left-toggle')

const rightToggle = document.getElementById('right-toggle')

const container = document.getElementById('container')

if (type === 'left') {

if (currentBgIndex - 1 < 0) {

currentBgIndex = 0

} else {

currentBgIndex -= 1

// leftToggle

}

} else {

// console.log(`ba`, backgroundList.length - 1)

if (currentBgIndex + 1 > backgroundList.length - 1) {

currentBgIndex = backgroundList.length - 1

} else {

currentBgIndex += 1

}

}

//给容器设置style ,把当前索引对应的图片设置为container的背景图

container.style.backgroundImage = `url(${backgroundList[currentBgIndex]})`

}

4、怎们封装一个方法

/**

* request 请求方法

* @param {*} config 请求配置

* config.url 请求路径

* config.method 请求方式

* config.headers 请求头

* config.data 请求参数

* config.onSuccess 请求成功回调

*/

config里面的method,header,data取出来放到options里面

这里的options就是作为fetch的第二个参数

function request(config) {

const baseUrl = `http://127.0.0.1:3550` // 域名

const options = {

method: config.method,

headers: config.headers || {} // config.headers存在时取config.headers 不存在时置为控对象

}

if ( config.method === 'post' ) {

// post请求的特殊处理

options.headers["Content-type"] = "application/x-www-form-urlencoded; charset=UTF-8"

options.body = config.data

}

fetch(`${baseUrl}${config.url}`, options)

.then((response) => {

// 把fetch返回的二进制流转换为json

return response.json()

}).then((json)=>{

config.onSuccess(json)

}).catch(err => {

console.log('Request Failed', err)

alert('接口请求失败,请检查')

});

}

// 完成一个接口请求之后,拿到返回数据,我们需要拿到后端返回的数据进行处理(暴露给调用方),

// 就需要用到回调函数 ,回调函数定义了一个方法,传了一个参数。config里面会传onsuccess,

// 请求成功后,调用这个onsuccess


// 举例

function add(a, b) {

return a + b

}

const num1 = 1

const num2 = 2

add(num1, num2)


四、怎么写一个接口

1、如何搭建一个后端服务

1、 Koa,node.js框架
npm,包管理器,类似于 python 中的pip。官方网站:https://www.npmjs.com/。在这里可以搜到前端常用的工具库或者框架等。
2、初始化npm目录:
npm init -y
执行完成之后,当前目录下会生成一个package.json文件。内容类似如下的形式。
{
  "name": "koa_study",
  "version": "1.0.0",
  "description": "npm,包管理器,类似于python中的pip。",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

3、当我们需要安装一个包时:
npm i koa
表示在当前目录下将koa安装为一个依赖。

4、设置npm源:
npm config set registry http://registry.npm.taobao.org/
或者在项目目录下添加.npmrc
registry=http://registry.npm.taobao.org/

2、怎么根据请求路径返回不同的数据

1、初始化,创建一个koa实例
// 引入koa
const Koa = require('koa');
// koa-bodyparser为了解析body里面的数据
var bodyParser = require('koa-bodyparser');
const app = new Koa();
app.use(bodyParser());
2、处理跨域
//ctx 上下文,可以处理请求和响应
app.use(async ctx => {
    // ctx.response(header)处理相应头,让所有域名可访问
    ctx.set('Access-Control-Allow-Origin', '*');
    let postParam = ctx.request.body
3、写接口
//判断请求路径
    const path = ctx.request.path
    if (path === '/user/login'){
        ctx.body = {
            code:0,
            data:{
                "username":postParam.userName,
                "password":postParam.password,
                "age": 12,
            },
            msg:'登录成功'
        };
        return     
    }

3、postman调用接口

请求URL:http://127.0.0.1:3500/user/login

演示

五、前端怎么调用后端接口

1、fetch方法

function handlelogin() {
    console.log('handlelogin')
    // const skipText = document.getElementsByClassName('reg-bar')[0]
    var opts = {
        method: "POST", //请求方法
        headers: {
            "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        },
        body: 'userName=rose&password=123456'
        // body: {
        //     userName: 'rose',
        //     password: '123456'
        // }
    }
    // 请求登录接口 fetch是一个promise(异步调用)
    fetch('http://127.0.0.1:3550/user/login', opts)
        .then((response) => {
            console.log('response', response)
            // 把fetch返回的二进制流转换为json
            return response.json()
        }).then((json) => {
            // 这里才能拿到真正的json数据
            console.log('json', json)
            if (json.code === 0) {
                const target = `./class_manage.html`
                window.open(target)
            } else {
                alert(json.msg)
            }
        })
        // 异常:接口写错,服务器挂了,代码问题...
        .catch(err => {
            console.log('Request Failed', err)
            alert('接口请求失败,请检查')
        });
}

跳转到公共request方法

2、怎么把后端返回的数据渲染到页面上

class_manage.js
/**
 * 请求课程列表数据
 * @returns 
 */
function handlleclass() {
    console.log('handlleclass')
    console.log('request', request)

    request({
        url: '/class/list',
        method: 'get',
        //请求成功回调,
        onSuccess: function(json) {
            if (json.code === 0) {
                // alert(json.msg)
                // 目标:把返回的数据渲染到页面上
                // 1. 找到目标元素,[0]就是取数组的第一个元素,getElementsByClassName返回的是一个数组
                // 同类:getElementById、getElementByName、getElementByTagName
                // 2. 遍历课程列表数组,组装成html字符串
                // 3. 把html字符串放进目标元素
                const classList = document.getElementByClassName('class-list')[0]
                console.log('classList', classList)
                let htmlStr = ''
                for (let index = 0; index < json.data.length; index++) {
                    htmlStr += `<dt>课程名称:
                    ${json.data[index]["title"]}
                    <button class="delete"
                        onclick="handleDeleteClass('${json.data[index].title}')"
                    >删除</button>
                    </dt>`
                }
                console.log(htmlStr);
                // 设置classList的内容为遍历取到的htmlStr数据
                classList.innerHTML = htmlStr
                // classList.append('888888')
            } else {
                alert(json.msg)
            }
            // 拿到数组后,遍历这个数组,组装成html.字符串
            // 遍历时,把每一条数据的titl写进去
        }
    })  

六、模拟常见的状态码

1、200

表示服务器已经成功接受请求,并将返回客户端所请求的最终结果

2、401

登录失效

//authorization获取不到权限时
//  ko_token/pc_user_key获取登录态
else if ( path === '/class/list/401' ) {
        if ( ctx.request.header.authorization ) {
            ctx.body = {
                code: 0,
                data: null,
                msg: 'success'
            }
        } else {
            ctx.status = 401
            return
        }
    }

3、405

Method Not Allowed

 //请求方式写错
 else if ( path === '/class/list/405' ) {
        if ( ctx.method !== 'GET' ) {
            ctx.status = 405
        } else {
            ctx.body = {
                code: 0,
                data: [],
                msg: 'success'
            }
        }
    }

4、500

服务器遇到未知的错误,导致无法完成客户端当前的请求

// eg:代码写错
else if ( path === '/class/list/500' ) {
        const classList = []
        ctx.body = {
            code: 0,
            data: {
                list: clasList
            },
            msg: ''
        }
    }

5、404

接口不存在

else if ( path === '/class/list/5003894u3894u3' ) {