inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

html과 파이썬으로 파라미터로 상세페이지 만들고 있는데 404가 뜨네요

441

foodgoder
0

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient
client = MongoClient("mongodb+srv://jykdb:jykdb@cluster0.udupui8.mongodb.net/?retryWrites=true&w=majority")
db = client.pirates_lv1

@app.route('/')
def home():
	return render_template("index.html")

@app.route('/exhibit/detail/<id>')
def detail():
    return render_template({"detail.html"})

@app.route('/exhibit', methods=["POST"])
def post_exhibit():

    url_receive = request.form["url_give"]
        
    headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get(url_receive, headers=headers)
    soup = BeautifulSoup(data.text, 'html.parser')

    title = soup.select_one('#container > div.wide-inner > section > h3').text
    period = soup.select_one('#container > div.detial-cont-element.active > div > dl:nth-child(1) > dd').text.strip()
    tags = soup.select_one('#container > section.tag-element.poi > p').text.replace('\n',' ')

    image = soup.select('.item')[1]['style'].replace("background-image:url('",'').replace("');",'')
    image = 'https://korean.visitseoul.net'+image
    post_list = list(db.exhibition.find({},{'_id':False}))
    count = len(post_list)+1
    doc = {
            'url': url_receive,
            'title':title,
            'period':period,
            'tags':tags,
            'image':image,
            'count': count
        }   

    db.exhibition.insert_one(doc)
    
    
    return jsonify({"msg": "완료!"})

@app.route('/exhibit', methods=["GET"])
def get_exhibit():
    exhibitions = list(db.exhibition.find({},{'_id':False}))
    return jsonify({"result": exhibitions})

@app.route('/exhibit/detail/<id>', methods=["GET"])
def detail(id):
	exhibition = db.exhibition.find_one({'count': int(id)}, {'_id': False})
	return render_template("detail.html", exhibition=exhibition)


if __name__ == "__main__":
	app.run(debug=True, port=8080)

위 코드는 제가 강의 보면서 만든 코드인데, chatgpt랑 대화해가면서 파라 미터를 활용한 상세페이지에 서버에서 불러온 데이터를 출력시키려고 하는데, 게시물 리스트에서 게시물 상세 페이지(detail.html)로 가면 404가 뜹니다. url에서는 이런식으로 잘 id값을 찾아오는데 말이죠. 아래가 게시물 상세페이지(detail.html) 자바스크립트 코드입니다.
무엇을 해야지 404 에러가 나지 않고 정상적으로 서버에서 데이터를 가져올 수 있을까요?

   <script>
            // URLSearchParams 객체 생성
            const urlParams = new URLSearchParams(window.location.search);
            // 'id' 파라미터 값 가져오기
            const id = urlParams.get('id');

            // 서버로부터 전시 정보 가져오기
            fetch(`/exhibit/detail/${id}`)
                .then((res) => res.json())
                .then((data) => {
                    let rows = data['result'];
                    rows.forEach((row) => {
                        const title = row.title;
                        const period = row.period;
                        const image = row.image;
                        const tags = row.tags;
                        const description = row.deco;
                        const temp_html = `
                        <div class="card">
                            <div style="background-image: url('${image}');" class="card-imag"></div>
                            <span class="title">${title}</span>
                            <span class="period">${tags}</span>
                            <span class="period">${description}</span>
                        </div>
                    `;
                        $('#card').prepend(temp_html);
                    });
                });
        </script>

답변 0