HTMX 및 Express.js를 사용하여 Rick and Morty 캐릭터 탐색기 구축

WBOY
풀어 주다: 2024-07-16 21:48:31
원래의
1072명이 탐색했습니다.

Wubba lubba 더빙 더빙 개발자 여러분! 웹 개발이라는 렌즈를 통해 Rick과 Morty의 광대한 다중우주를 탐험하는 것이 어떤 것인지 궁금한 적이 있습니까? 자, 포털 건을 들고 준비하세요. 오늘 우리는 바로 그 일을 할 것이기 때문입니다. 우리는 HTMX와 Express.js를 사용하여 Rick and Morty Character Explorer를 구축할 것입니다. 이 튜토리얼의 목표는 HTMX를 사용하여 웹 개발 및 페이지 매김 구현이 얼마나 쉬운지 보여주는 것입니다

이 모험에서 다룰 내용은 다음과 같습니다.

  • Express.js 서버 설정(다차원 여행 장치)
  • EJS 및 HTMX(포털 뷰어)를 사용하여 동적 프런트엔드 만들기
  • HTMX(차원 간 이동 방법)를 사용하여 원활한 서버측 페이지 매김 구현

초보 프로그래머이든 레벨 업을 원하는 노련한 개발자이든 이 가이드는 매우 인상적인 웹 앱을 만드는 데 도움이 될 것입니다.

다차원 작업대 설정

차원 간 이동을 시작하기 전에 차원 간 작업대를 설정해야 합니다. 이것을 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 Server 제작(Express.js 백엔드)

이제 Express.js 서버를 만들어 보겠습니다. 이는 포털 건의 엔진을 만드는 것과 같습니다. 이것이 차원 간 여행의 원동력입니다.

이 튜토리얼에서는 캐릭터 목록, 위치, 등장 에피소드를 가져올 수 있는 팬이 만든 Rick and Morty API를 사용할 것입니다. 또한 인기 있는 자바스크립트 템플릿인 ejs도 사용할 것입니다. 엔진을 사용하여 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 and Morty API에서 문자 데이터를 가져오는 곳입니다.

여기서 페이지 매김과 필터를 어떻게 처리하는지 살펴보세요. 페이지 매개변수는 우리가 요청하는 결과 페이지를 결정하고, 이름과 상태는 문자 필터링을 허용합니다. 이러한 유연성은 HTMX 페이지 매김 구현에 매우 중요합니다.

Multiverse Viewer 설계(EJS 및 HTMX를 사용한 프런트엔드)

우주 서버가 준비되면 다중우주를 볼 수 있는 방법이 필요합니다. 다차원적인 보기 화면과 효율적인 가젯 디자인인 EJS와 HTMX를 만나보세요.

HTMX는 JavaScript(React, Angular, Vue 등)를 작성하지 않고도 HTML에서 직접 AJAX, CSS 전환, WebSocket 및 서버 전송 이벤트에 액세스할 수 있는 새로운 JavaScript 라이브러리입니다. 마치 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를 한 줄도 작성하지 않고도 원활한 서버 측 페이지 매김을 구현할 수 있습니다. Rick의 포털 건처럼 원활하게 작동합니다. 링크를 클릭하면 즉시 다음 캐릭터 페이지로 이동합니다.

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!