使用Fetch API 实现学生信息的CRUD操作(4)---Fetch Api实战

背景

接着上一节,把Fetch Api 用起来。

预备知识

如果本节有些细节概念看上去有些吃力(尤其是promise),可以看一下:

什么是Fetch API

Fetch API 提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应。它还提供了一个全局 fetch()方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。(取代传统的XMLHttpRequest的) 这种功能以前是使用 XMLHttpRequest实现的。Fetch提供了一个更好的替代方法,可以很容易地被其他技术使用,例如 Service Workers。 Fetch 还利用到了请求的异步特性——它是基于Promise的。

简单说就是取代了Ajax,用来获取后台数据

为什么要使用Fetch API

传统的XMLHttpRequest请求闲的非常的杂乱,而优雅的ajax又不得不额外加载jQuery这个80K左右的框架 那么Fetch API就应势而生,提供了一种新规范,用来取代善不完美的 XMLHttpRequest 对象

浏览器发送HTTP请求:

  • 当用户在浏览器的地址栏中输入一个URL地址并按回车键之后,浏览器会向HTTP服务器发送HTTP请求。 当我们在浏览器输入URL http://www.baidu.com 的时候,浏览器发送一个Request请求去获取 http://www.baidu.com
    的html文件,服务器把Response文件对象发送回给浏览器。
  • 浏览器分析Response中的 HTML,发现其中引用了很多其他文件,比如Images文件,CSS文件,JS文件。 浏览器会自动再次发送Request去获取图片,CSS文件,或者JS文件等。
  • 当所有的文件都下载成功后,网页会根据HTML语法结构,完整的显示出来了。

如何使用

基础语法

fetch(url) // 调用fetch函数,将API的url作为参数传递
.then(function() {
    // 处理从API获取的数据
})
.catch(function() {
    // 如理服务器返回任何错误
});

创建本地数据库

创建db.json,使用json-server
启动起来

{
  "contacts3": [
    {
      "name": "FFF",
      "email": "2656593403@qq.com2",
      "contactno": "111111130",
      "id": 9
    },
    {
      "name": "PPP",
      "email": "asd@qq.com2",
      "contactno": "114130",
      "id": 10
    },
    {
      "name": "vvvvv",
      "email": "2656593403@qq.com2",
      "contactno": "111111130",
      "id": 99
    }
  ]
}

get 获取数据

需要指明是get请求

  1. 安装node-fetch

    npm i node-fetch --save
    
  2. test.js

    const fetch = require("node-fetch");
    fetch('http://localhost:3000/contacts3', {
        method: 'GET'
    })
        .then((res) => {
            return res.text() //res.text()是一个Promise对象
        })
        .then((res) => {
            console.log(res) // res是最终的结果
        })
    
  3. 命令行执行node test.json,结果
    在这里插入图片描述
    GET请求如何获取具体某个用户的数据?
    只用改写把URL,进行传递了
    eg:获取id=99这个用户的信息
    eg:http://localhost:3000/contacts3/99

post 添加数据

postman里面我们使用过post请求,需要加上一些参数

  • header

    headers: {
                'content-type': 'application/json' //数据类型是JSON
            },
    
  • body 添加的数据

    let data={
      "name": "kkk",
      "email": "sadad@qq.com2",
      "contactno": "asdsad",
      "id": 90
    }
    
  • 整体代码

    const fetch = require("node-fetch");
    const url = 'http://localhost:3000/contacts3';
    let data = {
        "name": "kkk",
        "email": "sadad@qq.com2",
        "contactno": "asdsad",
        "id": 90
    }
    
    fetch(url, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(data)//把对象通过stringify变成字符串,提交给后台或者存储db.json文件中
     
    }).then((res) => {
        return res.json() // 返回一个Promise,可以解析成JSON
    }).then((res) => {
        console.log(res) // 获取JSON数据
    })
    
  • 命令行执行 node test.js,返回如下

    { name: 'kkk', email: 'sadad@qq.com2', contactno: 'asdsad', id: 90 }
    

patch修改数据

const fetch = require("node-fetch");
const url = 'http://localhost:3000/contacts3';
let id = 9;
let data = {
    "name": "SSS",

}
fetch(url + `/${id}`, {
    method: 'PATCH',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(data)
}).then((res) => {
    return res.json()
}).then((res) => {
    console.log(res)
})

delete 删除数据

const fetch = require("node-fetch");
const url = 'http://localhost:3000/contacts3';
let id = 90;
fetch(url + `/${id}`, {
    method: 'DELETE',
}).then((res) => {
    return res.json()
}).then((res) => {
    console.log(res)
})

优化代码

之前CRUD的代码,我是放在了4个js文件里面,现在把他整合到一个js文件下,用一个测试文件调用它

  • 封装代码 All.js

const fetch = require("node-fetch");
function crudFetcdh(url, options, method = 'GET', data = {}) {
    url += options; //拼接url
    if (method === 'GET' || method === 'DELETE') {
        initObj = {
            method: method,
            credentials: 'include'  强制加入凭据头
        }
    } else {
        initObj = {
            method: method,
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify(data)

        }
    }
    //console.log(initObj);
    fetch(url, initObj).then((res) => {
        return res.json()
    }).then((res) => {
        console.log(res)
    }).catch(error => { console.log(error) }) //输出报错
}


function GET(url, options) {
    return crudFetcdh(url, options, 'GET')
}


function POST(url, data) {
    return crudFetcdh(url, options = "", 'POST', data)
}

function PATCH(url, options, data) {
    return crudFetcdh(url, options, 'PATCH', data)
}

function DELETE(url, options) {
    return crudFetcdh(url, options, 'DELETE')
}

module.exports = {
    GET,
    POST,
    PATCH,
    DELETE

}
  • 测试代码 Test.js
const fetch = require('./All.js');
fetch.GET('http://localhost:3000/contacts3/', 9);
fetch.DELETE('http://localhost:3000/contacts3/', 3);//如果id=3的用户不存在,输出报错信息
fetch.PATCH('http://localhost:3000/contacts3/', 9, {
    "name": "DDD"
});

fetch.POST('http://localhost:3000/contacts3/', {
    "name": "CCC",
    "email": "4345345353@qq.com2",
    "contactno": "1111130",
    //不写id,是因为会自动添加
});

参考链接

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data
https://segmentfault.com/a/1190000011433064
https://www.cnblogs.com/chengxs/p/8656723.html
https://www.cnblogs.com/paris-test/p/9719140.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LayUI是一个前端UI框架,不能直接用来对数据库进行CRUD操作,你需要使用后端语言(如PHP、Python、Java等)来实现对数据库的操作。以下是一个使用PHP语言和MySQL数据库进行学生表CRUD操作的例子: ``` <?php // 连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // 查询学生表 $sql = "SELECT * FROM student"; $result = mysqli_query($conn, $sql); // 输出学生表 echo "<table>"; echo "<tr><th>ID</th><th>Name</th><th>Age</th><th>Gender</th><th>Department</th></tr>"; while($row = mysqli_fetch_assoc($result)) { echo "<tr><td>" . $row["id"]. "</td><td>" . $row["name"]. "</td><td>" . $row["age"]. "</td><td>" . $row["gender"]. "</td><td>" . $row["department"]. "</td></tr>"; } echo "</table>"; // 添加学生 if(isset($_POST["name"]) && isset($_POST["age"]) && isset($_POST["gender"]) && isset($_POST["department"])) { $name = $_POST["name"]; $age = $_POST["age"]; $gender = $_POST["gender"]; $department = $_POST["department"]; $sql = "INSERT INTO student (name, age, gender, department) VALUES ('$name', $age, '$gender', '$department')"; if (mysqli_query($conn, $sql)) { echo "New student record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } } // 修改学生 if(isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["age"]) && isset($_POST["gender"]) && isset($_POST["department"])) { $id = $_POST["id"]; $name = $_POST["name"]; $age = $_POST["age"]; $gender = $_POST["gender"]; $department = $_POST["department"]; $sql = "UPDATE student SET name='$name', age=$age, gender='$gender', department='$department' WHERE id=$id"; if (mysqli_query($conn, $sql)) { echo "Student record updated successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } } // 删除学生 if(isset($_POST["delete_id"])) { $id = $_POST["delete_id"]; $sql = "DELETE FROM student WHERE id=$id"; if (mysqli_query($conn, $sql)) { echo "Student record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } } // 关闭数据库连接 mysqli_close($conn); ?> ``` 这个例子中,我们使用了PHP语言和MySQL数据库来实现对学生表的CRUD操作。我们通过查询学生表来输出学生信息,通过表单提交来添加学生、修改学生和删除学生。你需要根据自己的需要进行修改和完善。同时,你还需要使用LayUI前端框架来美化学生表的界面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值