首页  >  文章  >  web前端  >  使用 HTMX 和 Express.js 构建 Rick and Morty 角色资源管理器

使用 HTMX 和 Express.js 构建 Rick and Morty 角色资源管理器

WBOY
WBOY原创
2024-07-16 21:48:311185浏览

开发者们,Wubba lubba dub dub!您是否想过通过网络开发的视角探索《瑞克和莫蒂》的广阔多元宇宙会是什么样子?好吧,拿起你的传送门枪并做好准备,因为今天我们将这样做 - 我们将使用 HTMX 和 Express.js 构建一个 Rick 和 Morty 角色资源管理器。本教程的目标是展示使用 HTMX 进行 Web 开发和实现分页是多么容易

在这次冒险中,我们将介绍:

  • 设置 Express.js 服务器(我们的跨维度旅行设备)
  • 使用 EJS 和 HTMX(我们的门户查看器)创建动态前端
  • 使用 HTMX(我们在维度之间跳转的方法)实现平滑的服务器端分页

无论您是新手程序员还是希望提升水平的经验丰富的开发人员,本指南都将帮助您创建一个令人印象深刻的 Web 应用程序。

设置你的多维工作台

在我们开始在维度之间跳跃之前,我们需要设置我们的跨维度工作台。可以将其视为整理 Rick 的车库,但使用更少的死亡射线和更多的 JavaScript。

  1. 首先,确保您安装了 Node.js。如果没有,您可以从nodejs.org 下载它。
  2. 接下来,我们将设置项目目录并安装必要的包。打开终端并运行以下命令:
mkdir rick-and-morty-explorer
cd rick-and-morty-explorer
npm init -y
npm install express axios ejs
  1. 项目结构:组织我们的项目类似于安排 Rick 的小工具。这是一个基本结构:
rick-and-morty-explorer/
├── node_modules/
├── public/
│   └── styles.css
├── views/
│   └── index.ejs
├── package.json
└── server.js

现在我们的工作台已经设置完毕,让我们继续制作我们的宇宙服务器。

制作 Cosmic 服务器(Express.js 后端)

现在,让我们创建 Express.js 服务器。这就像建造我们传送门枪的引擎 - 它为我们的跨维度旅行提供动力。

在本教程中,我们将使用粉丝制作的 Rick 和 Morty API,它允许我们获取角色列表、他们的位置以及他们出现的剧集。我们还将使用 ejs,一种流行的 javascript 模板引擎,写出我们的 HTML。 ejs 不是必需的,但以干净且可重用的方式简化了 HTML 的编写。

打开server.js,让我们开始编码:

const express = require('express');
const axios = require('axios');
const app = express();

app.use(express.static('public'));
app.set('view engine', 'ejs');

const BASE_URL = 'https://rickandmortyapi.com/api/character';

app.get('/', async (req, res) => {
  const { page = 1, name, status } = req.query;
  let url = `${BASE_URL}?page=${page}`;

  if (name) url += `&name=${name}`;
  if (status) url += `&status=${status}`;

  try {
    const response = await axios.get(url);
    res.render('index', { data: response.data, query: req.query });
  } catch (error) {
    console.error('Error fetching data:', error.message);
    res.status(500).render('error', { message: 'Error fetching data' });
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));

这个服务器设置就像 Rick 的车库 - 这是所有魔法发生的地方。我们使用 Express 来创建服务器并处理路由。主路由 (/) 是我们根据查询参数从 Rick 和 Morty API 获取角色数据的地方。

请注意我们如何在这里处理分页和过滤器。 page 参数确定我们请求的结果页,而 name 和 status 允许过滤字符。这种灵活性对于我们的 HTMX 分页实现至关重要。

设计 Multiverse 查看器(使用 EJS 和 HTMX 的前端)

我们的宇宙服务器就位后,我们需要一种查看多元宇宙的方法。输入 EJS 和 HTMX——我们的多维观看屏幕和高效的小工具设计。

HTMX 是一个新的 JavaScript 库,允许您直接在 HTML 中访问 AJAX、CSS 转换、WebSocket 和服务器发送事件,而无需编写 JavaScript(React、Angular、Vue 等)。它就像 Rick 的神经植入物一样 — 它增强了 HTML 的功能,超出了您最疯狂的梦想。

在你的views/index.ejs 文件中,添加以下代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rick and Morty Explorer</title>
    <script src="https://unpkg.com/htmx.org@1.9.10"></script>
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
    <h1>Rick and Morty Character Explorer</h1>

     <!-- Filter section will go here -->

        <div id="character-table">
          <% if (data.results && data.results.length > 0) { %>
            <table>
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Name</th>
                        <th>Status</th>
                        <th>Species</th>
                        <th>Origin</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <% data.results.forEach(character => { %>
                        <tr>
                            <td><img src="<%= character.image %>" alt="<%= character.name %>" width="50"></td>
                            <td><%= character.name %></td>
                            <td><%= character.status %></td>
                            <td><%= character.species %></td>
                            <td><%= character.origin.name %></td>
                            <td><a href="/character/<%= character.id %>" hx-get="/character/<%= character.id %>" hx-target="body" hx-push-url="true">View More</a></td>
                        </tr>
                    <% }); %>
                </tbody>
            </table>

    <!-- Pagination section will go here -->
</body>
</html>

上面的代码为我们的网站设置了一个基本表格,我们将在下一节中使用 HTMX 添加分页和过滤。

实现多维分页

现在,让我们实现分页,这是我们应用程序的跨维度旅行机制。这就是 HTMX 真正闪光的地方,它使我们能够实现流畅的服务器端分页,而无需任何自定义 JavaScript。

将此分页部分添加到您的index.ejs,就在字符表之后:

<div class="pagination">
    <% const currentPage = parseInt(query.page) || 1; %>
    <% if (data.info.prev) { %>
        <a href="/?page=<%= currentPage - 1 %><%= query.name ? `&name=${query.name}` : '' %><%= query.status ? `&status=${query.status}` : '' %>"
           hx-get="/?page=<%= currentPage - 1 %><%= query.name ? `&name=${query.name}` : '' %><%= query.status ? `&status=${query.status}` : '' %>"
           hx-target="body"
           hx-push-url="true">Previous</a>
    <% } %>
    <span>Page <%= currentPage %> of <%= data.info.pages %></span>
    <% if (data.info.next) { %>
        <a href="/?page=<%= currentPage + 1 %><%= query.name ? `&name=${query.name}` : '' %><%= query.status ? `&status=${query.status}` : '' %>"
           hx-get="/?page=<%= currentPage + 1 %><%= query.name ? `&name=${query.name}` : '' %><%= query.status ? `&status=${query.status}` : '' %>"
           hx-target="body"
           hx-push-url="true">Next</a>
    <% } %>
</div>

这个分页部分是我们 HTMX 实现皇冠上的宝石。让我们来分解一下:

  • 我们计算当前页面并检查是否有上一页或下一页。
  • 每个链接上的 hx-get 属性告诉 HTMX 使用适当的页码和任何活动过滤器向我们的服务器发出 GET 请求。
  • hx-target="body" 确保导航时更新整个页面内容。
  • hx-push-url="true" 更新 URL,允许用户共享或为特定页面添加书签。

这个 HTMX 分页的美妙之处在于它的简单性和效率。我们能够实现流畅的服务器端分页,而无需编写一行自定义 JavaScript。它就像瑞克的传送枪一样无缝 - 单击链接,您会立即传送到下一页的角色。

通过利用 HTMX,我们创建了一个分页系统,该系统不仅易于实现,而且还提供流畅、类似应用程序的用户体验。它速度很快,可以在页面加载时保持状态,并且使用最少的 Javascript。

Crafting the Multiverse Filter

Let's take our interdimensional exploration to the next level by adding filters to our character explorer. Think of this as tuning into different channels on interdimensional cable – you want to find the right show (or character) amidst the multiverse chaos.

Add this filter section to your index.ejs file, right above the character table:

<form id="filter-form" hx-get="/" hx-target="body" hx-push-url="true">
    <input type="text" name="name" placeholder="Name" value="<%= query.name || '' %>">
    <select name="status">
        <option value="">All Statuses</option>
        <option value="alive" <%= query.status === 'alive' ? 'selected' : '' %>>Alive</option>
        <option value="dead" <%= query.status === 'dead' ? 'selected' : '' %>>Dead</option>
        <option value="unknown" <%= query.status === 'unknown' ? 'selected' : '' %>>Unknown</option>
    </select>
    <button type="submit">Filter</button>
</form>

These filters allow users to narrow down their search, just like Rick tuning his interdimensional cable to find the perfect show. Enhanced with the power HTMX, our filter implementation is powerful and intuitive, providing real-time updates without needing custom JavaScript. Our app with both filters and pagination should look like this:

Rick and Morty Explorer Web App

Creating Character Profiles: Adding the Details Screen

Now that our Rick and Morty Character Explorer looks slick and functional, it's time to add another exciting feature: individual character profiles. Imagine diving into a detailed dossier on Morty or Rick, complete with all their vital stats and episode appearances. Let's add a "View More" button to our character table to take users to a detailed character profile page.

Let's add a new route to our server.js file:

// Route to display character details
app.get('/character/:id', async (req, res) => {
  const { id } = req.params;

  try {
    const response = await axios.get(`${BASE_URL}/${id}`);
    res.render('character', { character: response.data });
  } catch (error) {
    console.error('Error fetching character details:', error.message);
    res.status(500).render('error', { message: 'Error fetching character details' });
  }
});

Let's also add a new file views/character.ejs the necessary HTML for our character detail page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= character.name %> - Details</title>
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
    <h1><%= character.name %> - Details</h1>
    <div class="character-details">
        <img src="<%= character.image %>" alt="<%= character.name %>">
        <ul>
            <li><strong>Status:</strong> <%= character.status %></li>
            <li><strong>Species:</strong> <%= character.species %></li>
            <li><strong>Gender:</strong> <%= character.gender %></li>
            <li><strong>Origin:</strong> <%= character.origin.name %></li>
            <li><strong>Location:</strong> <%= character.location.name %></li>
        </ul>
        <h2>Episodes</h2>
        <ul>
            <% character.episode.forEach(episode => { %>
                <li><a href="<%= episode %>" target="_blank">Episode <%= episode.split('/').pop() %></a></li>
            <% }); %>
        </ul>
    </div>
    <a href="/" hx-get="/" hx-target="body" hx-push-url="true" class="back-link">Back to Character List</a>
</body>
</html>

The code above defines a new route on our web server /character/:id. This new route is resolved when the user clicks on the view more option in the characters table. It fetches details for the specific character and returns a neatly rendered HTML page with all the character details. This page will look like this:
Character Detail Page

Putting It All Together: Your Interdimensional Character Explorer

Now that we've built our interdimensional travel device, it's time to see it in action. Here's a complete overview of our code, bringing together everything we've covered so far and also defining custom CSS styles to make the application look better.

Conclusion: Your Portal to Advanced Web Development

Congratulations—you've just built an interdimensional character explorer! In this adventure, we've covered a lot of ground, from setting up our Express.js server and designing a dynamic frontend with EJS and HTMX to implementing smooth pagination and filters.

This project is a testament to the power of HTMX. It shows how we can create dynamic, server-side rendered applications with minimal JavaScript. It's fast, efficient, and user-friendly—just like Rick's portal gun.

But don't stop here! There's a whole multiverse of possibilities waiting for you. Experiment with new features, add more filters or integrate additional APIs. The only limit is your imagination.

"Post-Credits Scene": Additional Resources and Easter Eggs

Before you go, here are some additional resources to help you on your journey:

  • HTMX Documentation
  • Express.js Documentation
  • Rick and Morty API

And for those who made it to the end, here are a few hidden Rick and Morty references:

  • Remember, "Wubba Lubba Dub Dub!" means you're in great pain, but also having a great time coding.
  • Lastly, always be like Rick – curious, inventive, and never afraid to break the rules (of JavaScript).

Happy coding, and may your interdimensional travels be filled with endless possibilities!

以上是使用 HTMX 和 Express.js 构建 Rick and Morty 角色资源管理器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn