Rick and Morty Character Explorer

<% if (data.results && data.results.length > 0) { %> <% data.results.forEach(character => { %> <% }); %>
Image Name Status Species Origin Actions
\\\"使用\\\" alt=\\\"<%= character.name %>\\\" width=\\\"50\\\"> <%= character.name %> <%= character.status %> <%= character.species %> <%= character.origin.name %> \\\" hx-target=\\\"body\\\" hx-push-url=\\\"true\\\">View More

The above code sets up a basic table for our website, we will add pagination and filtering using HTMX in the following section.

Implementing Interdimensional Pagination

Now, let\\'s implement pagination, our app\\'s interdimensional travel mechanism. This is where HTMX really shines, allowing us to implement smooth, server-side pagination without any custom JavaScript.

Add this pagination section to your index.ejs, just after the character table:

This pagination section is the crown jewel of our HTMX implementation. Let\\'s break it down:

The beauty of this HTMX pagination is its simplicity and efficiency. We\\'re able to implement smooth, server-side pagination without writing a single line of custom JavaScript. It\\'s as seamless as Rick\\'s portal gun – click a link, and you\\'re instantly transported to the next page of characters.

By leveraging HTMX, we\\'ve created a pagination system that\\'s not only easy to implement but also provides a smooth, app-like user experience. It\\'s fast, maintains state across page loads, and uses minimal 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:

\\\">

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

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 detailsapp.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:

            <%= character.name %> - Details        

<%= character.name %> - Details

\\\"使用\\\" alt=\\\"<%= character.name %>\\\">
  • Status: <%= character.status %>
  • Species: <%= character.species %>
  • Gender: <%= character.gender %>
  • Origin: <%= character.origin.name %>
  • Location: <%= character.location.name %>

Episodes

Back to Character List

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

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:

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

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

","image":"http://www.luping.net/uploads/424/1f1bb5f5a631e38294a42ac9fa5400ee.png","datePublished":"2024-08-09T09:00:03+08:00","dateModified":"2024-08-09T09:00:04+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 HTMX 和 Express.js 构建 Rick and Morty 角色资源管理器

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

发布于2024-08-09
浏览:356

Wubba lubba dub dub, developers! Have you ever wondered what it would be like to explore the vast multiverse of Rick and Morty through the lens of web development? Well, grab your portal guns and get ready, because today we'll do just that – we're going to build a Rick and Morty Character Explorer using HTMX and Express.js. The goal of this tutorial is to show how easy it is to do web dev and implement pagination using HTMX

In this adventure, we'll cover:

  • Setting up an Express.js server (our interdimensional travel device)
  • Creating a dynamic frontend with EJS and HTMX (our portal viewer)
  • Implementing smooth, server-side pagination with HTMX (our method of jumping between dimensions)

Whether you're a rookie programmer or a seasoned dev looking to level up, this guide will help you create a web app that's burp seriously impressive.

Setting Up Your Interdimensional Workbench

Before we can start hopping between dimensions, we need to set up our interdimensional workbench. Think of this as organizing Rick's garage but with fewer death rays and more JavaScript.

  1. First, ensure you have Node.js installed. If not, you can download it from nodejs.org.
  2. Next, we'll set up our project directory and install the necessary packages. Open your terminal and run the following commands:
mkdir rick-and-morty-explorer
cd rick-and-morty-explorer
npm init -y
npm install express axios ejs
  1. Project Structure: Organizing our project is akin to arranging Rick's gadgets. Here's a basic structure:
rick-and-morty-explorer/
├── node_modules/
├── public/
│   └── styles.css
├── views/
│   └── index.ejs
├── package.json
└── server.js

Now that our workbench is set up, let's move on to crafting our cosmic server.

Crafting the Cosmic Server (Express.js Backend)

Now, let's create our Express.js server. This is like building the engine of our portal gun - it's what powers our interdimensional travels.

In this tutorial, we shall be using a fan-made Rick and Morty API that allows us to fetch a list of characters, their locations, and the episodes they appeared in. We will also be using ejs, a popular javascript templating engine, to write out our HTML. ejs is not required but simplifies writing our HTML in a clean and reusable way.

Open up server.js, and let's get coding:

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'));

This server setup is like Rick's garage – it's where all the magic happens. We're using Express to create our server and handle routing. The main route (/) is where we'll fetch character data from the Rick and Morty API based on the query parameters.

Notice how we're handling pagination and filters here. The page parameter determines which page of results we're requesting, while name and status allow for filtering characters. This flexibility is crucial for our HTMX pagination implementation.

Designing the Multiverse Viewer (Frontend with EJS and HTMX)

With our cosmic server in place, we need a way to view the multiverse. Enter EJS and HTMX—our multidimensional viewing screen and efficient gadget designs.

HTMX is a new JavaScript library that allows you to access AJAX, CSS Transitions, WebSockets, and Server-Sent Events directly in HTML without writing JavaScript (React, Angular, Vue, etc.). It's like Rick's neural implant—it enhances HTML's capabilities beyond your wildest dreams.

In your views/index.ejs file, add the following code:



    Rick and Morty Explorer

Rick and Morty Character Explorer

0) { %> { %>
Image Name Status Species Origin Actions
" alt="" width="50"> " hx-target="body" hx-push-url="true">View More

The above code sets up a basic table for our website, we will add pagination and filtering using HTMX in the following section.

Implementing Interdimensional Pagination

Now, let's implement pagination, our app's interdimensional travel mechanism. This is where HTMX really shines, allowing us to implement smooth, server-side pagination without any custom JavaScript.

Add this pagination section to your index.ejs, just after the character table:


This pagination section is the crown jewel of our HTMX implementation. Let's break it down:

  • We calculate the current page and check if there are previous or next pages.
  • The hx-get attribute on each link tells HTMX to make a GET request to our server with the appropriate page number and any active filters.
  • hx-target="body" ensures that the entire page content is updated when navigating.
  • hx-push-url="true" updates the URL, allowing users to share or bookmark specific pages.

The beauty of this HTMX pagination is its simplicity and efficiency. We're able to implement smooth, server-side pagination without writing a single line of custom JavaScript. It's as seamless as Rick's portal gun – click a link, and you're instantly transported to the next page of characters.

By leveraging HTMX, we've created a pagination system that's not only easy to implement but also provides a smooth, app-like user experience. It's fast, maintains state across page loads, and uses minimal 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:

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:



     - Details

- Details

" alt="">
  • Status:
  • Species:
  • Gender:
  • Origin:
  • Location:

Episodes

Back to Character List

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!

版本声明 本文转载于:https://dev.to/mikeyny_zw/building-a-rick-and-morty-character-explorer-with-htmx-and-expressjs-12n3?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • Polyfills——填充物还是缝隙? (第 1 部分)
    Polyfills——填充物还是缝隙? (第 1 部分)
    几天前,我们在组织的 Teams 聊天中收到一条优先消息,内容如下:发现安全漏洞 - 检测到 Polyfill JavaScript - HIGH。 举个例子,我在一家大型银行公司工作,你必须知道,银行和安全漏洞就像主要的敌人。因此,我们开始深入研究这个问题,并在几个小时内解决了这个问题,我将在下面...
    编程 发布于2024-11-05
  • 移位运算符和按位简写赋值
    移位运算符和按位简写赋值
    1。移位运算符 :向右移动。 >>>:无符号右移(零填充)。 2.移位运算符的一般语法 value > num-bits:将值位向右移动,保留符号位。 value >>> num-bits:通过在左侧插入零将值位向右移动。 3.左移 每次左移都会导致该值的所有位向左移动一位。 右侧插入0位。 效果:...
    编程 发布于2024-11-05
  • 如何使用 VBA 从 Excel 建立与 MySQL 数据库的连接?
    如何使用 VBA 从 Excel 建立与 MySQL 数据库的连接?
    VBA如何在Excel中连接到MySQL数据库?使用VBA连接到MySQL数据库尝试连接使用 VBA 在 Excel 中访问 MySQL 数据库有时可能具有挑战性。在您的情况下,您在尝试建立连接时遇到错误。要使用 VBA 成功连接到 MySQL 数据库,请按照下列步骤操作:Sub ConnectDB...
    编程 发布于2024-11-05
  • 测试自动化:使用 Java 和 TestNG 进行 Selenium 指南
    测试自动化:使用 Java 和 TestNG 进行 Selenium 指南
    测试自动化已成为软件开发过程中不可或缺的一部分,使团队能够提高效率、减少手动错误并以更快的速度交付高质量的产品。 Selenium 是一个用于自动化 Web 浏览器的强大工具,与 Java 的多功能性相结合,为构建可靠且可扩展的自动化测试套件提供了一个强大的框架。使用 Selenium Java 进...
    编程 发布于2024-11-05
  • 我对 DuckDuckGo 登陆页面的看法
    我对 DuckDuckGo 登陆页面的看法
    “你为什么不谷歌一下呢?”是我在对话中得到的常见答案。谷歌的无处不在甚至催生了新的动词“谷歌”。但是我编写的代码越多,我就越质疑我每天使用的数字工具。也许我对谷歌使用我的个人信息的方式不再感到满意。或者我们很多人依赖谷歌进行互联网搜索和其他应用程序,说实话,我厌倦了在搜索某个主题或产品后弹出的广告,...
    编程 发布于2024-11-05
  • 为什么 Turbo C++ 的“cin”只读取第一个字?
    为什么 Turbo C++ 的“cin”只读取第一个字?
    Turbo C 的“cin”限制:仅读取第一个单词在 Turbo C 中,“cin”输入运算符有一个处理字符数组时的限制。具体来说,它只会读取直到遇到空白字符(例如空格或换行符)。尝试读取多字输入时,这可能会导致意外行为。请考虑以下 Turbo C 代码:#include <iostream....
    编程 发布于2024-11-05
  • 使用 Buildpack 创建 Spring Boot 应用程序的 Docker 映像
    使用 Buildpack 创建 Spring Boot 应用程序的 Docker 映像
    介绍 您已经创建了一个 Spring Boot 应用程序。它在您的本地计算机上运行良好,现在您需要将该应用程序部署到其他地方。在某些平台上,您可以直接提交jar文件,它将被部署。在某些地方,您可以启动虚拟机,下载源代码,构建并运行它。但是,大多数时候您需要使用容器来部署应用程序。大...
    编程 发布于2024-11-05
  • 如何保护 PHP 代码免遭未经授权的访问?
    如何保护 PHP 代码免遭未经授权的访问?
    保护 PHP 代码免遭未经授权的访问保护 PHP 软件背后的知识产权对于防止其滥用或盗窃至关重要。为了解决这个问题,可以使用多种方法来混淆和防止未经授权的访问您的代码。一种有效的方法是利用 PHP 加速器。这些工具通过缓存频繁执行的部分来增强代码的性能。第二个好处是,它们使反编译和逆向工程代码变得更...
    编程 发布于2024-11-05
  • React:了解 React 的事件系统
    React:了解 React 的事件系统
    Overview of React's Event System What is a Synthetic Event? Synthetic events are an event-handling mechanism designed by React to ach...
    编程 发布于2024-11-05
  • 为什么在使用 Multipart/Form-Data POST 请求时会收到 301 Moved Permanently 错误?
    为什么在使用 Multipart/Form-Data POST 请求时会收到 301 Moved Permanently 错误?
    Multipart/Form-Data POSTs尝试使用 multipart/form-data POST 数据时,可能会出现类似所提供的错误消息遭遇。理解问题需要检查问题的构成。遇到的错误是 301 Moved Permanently 响应,表明资源已被永久重定向。当未为 multipart/f...
    编程 发布于2024-11-05
  • 如何使用日期和时间对象确定 PHP 中的时间边界?
    如何使用日期和时间对象确定 PHP 中的时间边界?
    确定 PHP 中的时间边界在此编程场景中,我们的任务是确定给定时间是否在预定义的范围内。具体来说,我们得到三个时间字符串:当前时间、日出和日落。我们的目标是确定当前时间是否位于日出和日落的边界时间之间。为了应对这一挑战,我们将使用 DateTime 类。这个类使我们能够表示和操作日期和时间。我们将创...
    编程 发布于2024-11-05
  • 如何使用 CSS 变换比例修复 jQuery 拖动/调整大小问题?
    如何使用 CSS 变换比例修复 jQuery 拖动/调整大小问题?
    jQuery 使用 CSS 变换缩放拖动/调整大小问题: 当应用 CSS 变换时,特别是变换:矩阵(0.5, 0, 0, 0.5, 0, 0);,对于一个 div 并在子元素上使用 jQuery 的draggable() 和 resizing() 插件,jQuery 所做的更改变得与鼠标位置“不同步...
    编程 发布于2024-11-05
  • 如何修复 TensorFlow 中的“ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型浮点)”错误?
    如何修复 TensorFlow 中的“ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型浮点)”错误?
    TensorFlow:解决“ValueError: Failed to Convert NumPy Array to Tensor (Unsupported Object Type Float)”工作时遇到的常见错误TensorFlow 的错误是“ValueError:无法将 NumPy 数组转换为...
    编程 发布于2024-11-05
  • 如何高效判断本地存储项是否存在?
    如何高效判断本地存储项是否存在?
    确定本地存储项目是否存在使用 Web 存储时,在访问或修改特定项目之前验证它们是否存在至关重要。在本例中,我们想要确定 localStorage 中是否设置了特定项目。当前方法检查项目是否存在的当前方法似乎是:if (!(localStorage.getItem("infiniteScro...
    编程 发布于2024-11-05
  • Java 中的原子是什么?了解 Java 中的原子性和线程安全
    Java 中的原子是什么?了解 Java 中的原子性和线程安全
    1. Java 原子简介 1.1 Java 中什么是原子? 在Java中,java.util.concurrent.atomic包提供了一组支持对单个变量进行无锁线程安全编程的类。这些类统称为原子变量。最常用的原子类包括 AtomicInteger 、 Atomic...
    编程 发布于2024-11-05

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3