커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
4주차 숙제 - 팬명록
undefined주차
북마크
황*연
댓글
5
추천
0
조회수
9
조회수
9
답변 완료

* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.

* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.


제가 name을 music으로, comment를 feeling로 변경하여 숙제를 진행중인데요.


console 창에

  • Uncaught SyntaxError: Lexical declaration cannot appear in a single-statement context (at (index):94:25) (index):126
  • Uncaught ReferenceError: save_feeling is not defined at HTMLButtonElement.onclick ((index):126:77) onclick @ (index):126


이런 오류메세지가 뜨면서 버튼을 눌러도 실행되지 않습니다. 코드상 어디에 문제가 있는건가요..?




스파르타 즉문즉답





작성한 코드 및 에러 메세지


<app.py>

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

from pymongo import MongoClient
import certifi
ca=certifi.where()
client = MongoClient('mongodb+srv://test:siyeon@cluster0.ajjhne8.mongodb.net/Cluster0?retryWrites=true&w=majority',tlsCAFile=ca)
db = client.dbsparta

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

@app.route("/homework", methods=["POST"])
def homework_post():
    music_receive = request.form["music_give"]
    feeling_receive = request.form["feeling_give"]

    doc={
        'music': music_receive,
        'feeling': feeling_receive
    }

    db.homework.insert_one(doc)
    return jsonify({'msg':'작성 완료!'})

@app.route("/homework", methods=["GET"])
def homework_get():
    feeling_list=list(db.homework.find({}, {'_id': False}))
    return jsonify({'feelings': feeling_list})

if __name__ == '__main__':
   app.run('0.0.0.0', port=5000, debug=True)


<index.html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

    <title>what music what feelings - 팬명록</title>

    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@200;300;400;500;600;700;900&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'NanumSquareRound';
            src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_two@1.0/NanumSquareRound.woff') format('woff');
            font-weight: normal;
            font-style: normal;
        }

        .mypic {
            width: 100%;
            height: 300px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://www.sbs.com.au/popasia/sites/sbs.com.au.popasia/files/styles/big_picture/public/dscf0330_c.jpg?itok=eQk8f_qR');
            background-position: center 50%;
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .mypost {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 20px auto;

            box-shadow: 0px 0px 3px 0px black;
            padding: 20px;
        }

        .mypost > button {
            margin-top: 15px;
        }

        .mycards {
            width: 95%;
            max-width: 500px;
            margin: auto;
        }

        .mycards > .card {
            margin-top: 10px;
            margin-bottom: 10px;
        }
    </style>
    <script>
        $(document).ready(function(){
            show_feeling()
        });

        function save_feeling(){
            let music = $('#music').val()
            let feeling = $('#feeling').val()

            $.ajax({
                type: 'POST',
                url: '/homework',
                data: {'music_give':music, 'feeling_give':feeling},
                success: function (response) {
                    alert(response["msg"])
                    window.location.reload()
                }
            })
        }
        function show_feeling(){
            $('#feeling-list').empty()
            $.ajax({
                type: "GET",
                url: "/homework",
                data: {},
                success: function (response) {
                    let rows = response['feelings']
                    for (let i=0; rows.length; i++)
                        let music = rows[i]['music']
                        let feeling = rows[i]['feeling']

                        let temp_html=` <div class="card">
                                            <div class="card-body">
                                                <blockquote class="blockquote mb-0">
                                                    <p>${feeling}</p>
                                                    <footer class="blockquote-footer">${music}</footer>
                                                </blockquote>
                                            </div>
                                        </div>`
                    $('feeling-list').append(temp_html)
                }
            });
        }
    </script>
</head>
<body>
    <div class="mypic">
        <h1>Music&Feelings</h1>
        <p>현재기온: <span id="temp">36</span></p>
    </div>
    <div class="mypost">
        <div class="form-floating mb-3">
            <input type="text" class="form-control" id="music" placeholder="url">
            <label for="floatingInput">music</label>
        </div>
        <div class="form-floating">
            <textarea class="form-control" placeholder="Leave a feeling here" id="feeling"
                style="height: 100px"></textarea>
            <label for="floatingTextarea2">feelings</label>
        </div>
        <button onclick="save_feeling()" type="button" class="btn btn-dark">memo</button>
    </div>
    <div class="mycards" id="feeling-list">
    </div>
</body>
</html>


<파이참 내 오류 메세지>


"/Users/siyeon/Downloads/스파르타 웹개발/projects/homework/venv/bin/python" /Users/siyeon/Downloads/스파르타 웹개발/projects/homework/app.py 

 * Serving Flask app 'app'

 * Debug mode: on

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.

 * Running on all addresses (0.0.0.0)

 * Running on http://127.0.0.1:5000

 * Running on http://192.168.35.181:5000

Press CTRL+C to quit

 * Restarting with stat

 * Debugger is active!

 * Debugger PIN: 605-972-301

127.0.0.1 - - [21/Dec/2022 13:03:47] "GET / HTTP/1.1" 200 -


취소
 공유
취소
댓글 0
댓글 알림
나의얼굴