全栈入门:使用 Fetch 实现前后端交互

在全栈开发中,前后端交互是至关重要的。通过 Fetch API,我们可以在前端轻松地发送请求到后端,并处理返回的数据。下面是一个简单的例子,哈士奇将展示如何使用 Fetch 在前端和后端之间进行交互。

后端搭建

首先,我们使用 json-server 快速搭建一个后端服务。在项目目录下执行以下命令:

bash 复制代码
npm init -y
npm install json-server --save-dev

然后,在项目根目录创建一个名为 db.json 的文件,用于存储我们的数据。示例数据如下:

json 复制代码
{
  "posts": [
    {
      "id": "1",
      "title": "你不知道的JavaScript",
      "author": "kyle simpson"
    },
    {
      "id": "2",
      "title": "JavaScript高级程序设计",
      "author": "Nicholas C.Zakas"
    },
    {
      "id": "b9ea",
      "title": "ES6标准入门",
      "author": "阮一峰"
    }
  ],
  "comments": [
    {
      "id": "1",
      "body": "好书!",
      "postId": 1
    },
    {
      "id": "2",
      "body": "好书!",
      "postId": 2
    }
  ]
}

接着,在 package.json 中添加一个启动脚本:

json 复制代码
"scripts": {
  "dev": "json-server --watch db.json --port 3000"
}

运行 npm run dev 启动 json-server,在端口 3000 上提供数据服务。

前端实现

现在,我们来编写前端代码,使用 Fetch 从后端获取数据。假设我们要展示所有的文章列表。我们可以这样做:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <!-- 语义化标签 seo 网络爬虫 -->
    <table class="table">
        <caption>文章表</caption>
        <!-- 表头 -->
        <thead>
            <tr>
                <th>序号</th>
                <th>标题</th>
                <th>作者</th>
                
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <!-- <ul id="posts"></ul> -->
    <form name="postForm">
        <div class="form-group">
            <label for="titleInput">标题</label>
            <input type="text" class="form-control"
            id="titleInput" placeholder="请输入标题">
        </div>
        <div class="form-group">
            <label for="authorInput">作者</label>
            <input type="text" class="form-control"
            id="authorInput" placeholder="请输入作者">
        </div>
        <button class="btn btn-default" type="submit">添加</button>
    </form>
</body>
<script>
    fetch('http://localhost:3000/posts')
        .then(res => res.json())
        .then(data=>{
            document.querySelector('.table tbody').innerHTML = data.map((post,index=0) => `
            <tr>
                <td>${index+1}</td>
                <td>${post.title}</td>
                <td>${post.author}</td>
            </tr>
            `).join('')
        })
        const oForm = document.forms["postForm"];
        oForm.addEventListener('submit', function(e){
            e.preventDefault();
            const newPost={
                'title': oForm.querySelector('#titleInput').value,
                'author': oForm.querySelector('#authorInput').value
            }
          fetch('http://localhost:3000/posts',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body:JSON.stringify(newPost),
          }).then(res=>res.json())
            .then(data=>{
                console.log(data);
            })
        })
</script>
</html>

解析

这段代码是一个简单的前端页面,使用了Bootstrap来美化界面,并通过Fetch API与后端进行交互,实现了展示文章列表和添加新文章的功能。让我逐步解释一下这段代码的关键部分:

  1. 引入Bootstrap样式:

    html 复制代码
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    这行代码引入了Bootstrap的CSS文件,用于美化页面样式。

  2. 展示文章列表:

    html 复制代码
    <tbody>
        <!-- 这里的文章列表将会被动态填充 -->
    </tbody>

    页面中使用了一个表格,用于展示文章列表。文章列表将会在后续的JavaScript代码中动态填充。

  3. 添加新文章表单:

    html 复制代码
    <form name="postForm">
        <!-- 输入文章标题的文本框 -->
        <input type="text" class="form-control" id="titleInput" placeholder="请输入标题">
        <!-- 输入文章作者的文本框 -->
        <input type="text" class="form-control" id="authorInput" placeholder="请输入作者">
        <!-- 提交按钮 -->
        <button class="btn btn-default" type="submit">添加</button>
    </form>

    这部分代码创建了一个表单,用于添加新的文章。用户可以在文本框中输入文章标题和作者,并点击提交按钮来添加文章。

  4. 使用Fetch获取文章列表并展示:

    javascript 复制代码
    fetch('http://localhost:3000/posts')
        .then(res => res.json())
        .then(data => {
            document.querySelector('.table tbody').innerHTML = data.map((post, index) => `
                <tr>
                    <td>${index + 1}</td>
                    <td>${post.title}</td>
                    <td>${post.author}</td>
                </tr>
            `).join('');
        })
        .catch(error => console.error('Error:', error));

    这段代码使用Fetch API向后端发送GET请求,获取文章列表数据。然后将获取的数据动态地填充到表格中,包括序号、标题和作者。

    这里需要对<td>${index + 1}</td>进行解释一下,如果在这里使用了<td>${post.id}</td>进行序号输出的话会导致出现乱码,因为我们在后面添加的过程中没有添加添加序号的代码

  5. 添加新文章并提交到后端:

    javascript 复制代码
    const oForm = document.forms["postForm"];
    oForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const newPost = {
            'title': oForm.querySelector('#titleInput').value,
            'author': oForm.querySelector('#authorInput').value
        };
        fetch('http://localhost:3000/posts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(newPost)
        })
        .then(res => res.json())
        .then(data => {
            console.log(data);
        });
    });

    这部分代码监听了表单的提交事件,当用户点击提交按钮时,阻止表单的默认提交行为,并将输入的文章标题和作者组成一个新的文章对象。然后使用Fetch API向后端发送POST请求,将新的文章数据提交到后端。提交成功后,会在控制台打印出返回的数据。

通过以上代码,我们实现了一个简单的前端界面,用于展示文章列表并添加新文章,与后端通过Fetch API进行数据交互。

效果

假如您也和我一样,在准备春招。欢迎加我微信 hcj1233223 ,这里有几十位一心去大厂的友友可以相互鼓励,分享信息,模拟面试,共读源码,齐刷算法,手撕面经。来吧,友友们!"

相关推荐
铁皮饭盒6 小时前
用 Bun.cron 定时 7 月 7 日,为啥? 看图1
javascript
Coder_Shenshen7 小时前
西门子S7CommPlus协议鉴权算法原理与流程详解
网络·后端·算法
大圣编程8 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
yuhaiqiang8 小时前
随手 vibecoding 的浏览器插件已经 6000 多次下载,聊聊他的产品设计
前端·后端·面试
之歆8 小时前
Vue商品详情与放大镜组件
前端·javascript·vue.js
再吃一根胡萝卜9 小时前
如何把小米 MiMo 接入 CodeBuddy,打造私有 Agent
前端
geovindu9 小时前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
负责的蛋挞10 小时前
异步HttpModule的实现方式
java·服务器·前端
卷无止境11 小时前
C++ 存储类说明符(Storage Class Specifier)大横评
c++·后端
用户0190275816111 小时前
量化数据的 batch 接口有多好用?从 1 只到 500 只,批量拉数据的正确姿势
后端