기본 콘텐츠로 건너뛰기

node.js DB연동 - 데이터 추가, 수정



1
2
3
4
5
6
7
8
9
10
11
12
app.get('/'function (request, response) {
    fs.readFile('list.html''utf8'function (error, data) {
        client.query('SELECT * FROM products'function (error, results) {
            response.send(ejs.render(data, {
                data : results
         
            }));
         
        });
    });
});
 
cs
cs
페이지 초기 진입시 띄어주는 부분.....
DB목록을 보여준다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
 
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>List Page</title>
</head>
<body>
    <h1>List Page</h1>
    <a href="/insert">INSERT DATA</a>
    <hr/>
    <table width="100%" border="1">
        <tr>
            <th>DELETE</th>
            <th>EDIT</th>
            <th>ID</th>
            <th>NAME</th>
            <th>Model Number</th>
            <th>Series</th>
        </tr>
        <%data.forEach(function(item, index){%>
        <tr>
            <td><a href="/delete/<%= item.id%>">DELETE</a></td>
            <td><a href="/edit/<%= item.id%>">INSERT</a></td>
            <td><%= item.id%></td>
            <td><%= item.name%></td>
            <td><%= item.modelnumber%></td>
            <td><%= item.series%></td>
        </tr>
        <%});%>
    </table>
</body>
</html>
cs
list.html문서


목록페이지 
아무생각 없이 삭제를 눌렀더니 다 사라졌다 ㅋㅋㅋㅋㅋㅋㅋ

 


1
2
3
4
5
6
app.get('/delete/:id'function (request, response) {
     client.query('DELETE FROM products WHERE id=?', [request.param('id')], function () {
         response.redirect('/');
    });
});
 
cs
cs
삭제시 삭제 쿼리문 실행
삭제를 한후 삭제된 것을 보여주기 위해 response.redirect('/');를 해서 다시 초기 페이지를 띄어준다.
삭제한 후 DB table을 확인해보면 데이터가 삭제됨을 확인을 할 수 있다.




1
2
3
4
5
app.get('/insert'function (request, response) {
    fs.readFile('insert.html''utf8'function (error, data) {
        response.send(data);
    });
});
cs
cs


1
2
3
4
5
6
7
8
app.post('insert'function (request, response) {
    var body = request.body;
    
    client.query('INSERT INTO products(name, modelnymber, series) VALUES (?,?,?)', [body.name, body.modelnmber, body.series], function () {
        response.redirect('/');
    });
});
 
cs
cs
데이터 추가 부분은 주소창에서 /insert를 직접 치고 들어가도 되고
INSERT DATA늘 눌러서 POST방식으로 페이지를 접근을 하게 해야 된다.(다양한 방식으로 접근이 가능하도록)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<head>
    <meta charset="utf-8" />
    <title>insert Page</title>
</head>
<body>
    <h1>Insert Page</h1>
    <hr />
    <from method="post">
        <fieldset>
            <table>
                <tr>
                    <td><label>name</label></td>
                    <td><input type="text" name="name"/></td>
                </tr>
                <tr>
                    <td><label>model number</label></td>
                    <td><input type="text" name="modelnumber" /></td>
                </tr>
                <tr>
                    <td><label>series</label></td>
                    <td><input type="text" name="series" /></td>
                </tr>
            </table>
            <input type="submit" />
        </fieldset>
    </from>
</body>
</html>
cs
inset.html 페이지

 
제출을 누르면 POST전송이 된다
근데 나는 안된다... 하하

씁.... ㅋㅋㅋㅋ
 



1
2
3
4
5
6
7
8
9
10
11
app.get('/edit/:id'function (request, response) {
    fs.readFile('edit.html''utf8'function (error, data) {
        client.query('SELECT * FROM products WHERE id =?', [
            request.param('id')
        ], function (error, result) {
            response.send(ejs.render(data, {
                data: result[0]
            }));
        });
    });
});
cs
get부분


1
2
3
4
5
6
7
8
9
10
11
app.post('/edit/:id'function (request, response) {
    var body = request.body
    
    client.query('UPDATE products SET name=?, modelnumber=?, series=? WHERE id=?', [
        body.name, body.modelnumber, body.series, request.param('id')
    ], function () {
        response.redirect('/');
    });
});
 
 
cs
cs
post부분


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
 
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Edit Page</title>
</head>
<body>
    <h1> Edit Page</h1>
    <hr />
    <form method="post">
        <fieldset>
 
            <legend>Edit Data</legend>
            <table>
                <tr>
                    <td><label>ID</label></td>
                    <td><input type="text" name="id" value="<%=data.id %>" disabled/></td>
                </tr>
                <tr>
                    <td><label>Name</label></td>
                    <td><input type="text" name="name" value="<%=data.name %>"  /></td>
                </tr>
                <tr>
                    <td><label>Model Number</label></td>
                    <td><input type="text" name="modelnumber" value="<%=data.modelnumber %>" /></td>
                </tr>
                <tr>
                    <td><label>Series</label></td>
                    <td><input type="text" name="Series" value="<%=data.Series %>" /></td>
                </tr>
            </table>
            <input type="submit" />
        </fieldset>
    </form>
</body>
</html>
cs
edit.html 페이지 문서

 

여기까지는 잘 되는데

전체적으로 post요청이 말을 안듣네 ㅋㅋㅋㅋ

 
씁씁하네ㅜㅠ

왜 안될까?

이것만 되면 기본적인 DB는 되는거 같은데;;;;;;;
모바일로 접속 정상 접속은 된다.


같은 에러 메시지가 뜬다... 
흠........ 코드를 다시 좀 봐야겠다..
moon_and_james-48

 

댓글

이 블로그의 인기 게시물

[node.js] 파일 리더기 만들기 - 사용 모듈 정리, pdf 구조, hwp 구조

pdf -> html 변환 가장 무난하다. 기본적으로 pdf는 htm와 비슷한 형태의 구조를 가지고 있다. 크게 header , body , xref table , trailer 의 구조로 되어있다. pdf는 환경에 상관없이 표현을 하기 위한 목적을 가지고 있는 파일이다. 이런 이유 때문에 무난히 진행이 된 것 같다. pdf2htmlex와 pdftohtmljs라는 모듈을 이용을 했다. var pdftohtml = require ( 'pdftohtmljs' ) ; var converter = new pdftohtml ( 'test.pdf' , "sample.html" ) ; converter . convert ( 'ipad' ) . then ( function ( ) { console . log ( "Success" ) ; } ) . catch ( function ( err ) { console . error ( "Conversion error: " + err ) ; } ) ; 이미지나, text같은 것들이 거의 100%로 변환이 된다. docx -> html 변환 docx파일을 html파일로 변환을 할 때는 style 적용과 한글이 깨지는 문제가 있다. 텍스트들을 전부 잘 읽기는 하는데 스타일 정보를 제대로 가져오지 못하기 때문에 좀 애매하다 - Headings. - Lists. - Customisable mapping from your own docx styles to HTML. For instance, you could convert WarningHeading to h1.warning by providing an appropriate style ...

[css] css로 프린트 방지하기

웹에서 프린트 제어가 불가능 한 줄 알았는데 프린트 클릭 시  스크립트로 해당 이벤트를 받아올 수 있다. 하지만 스크립트를 사용하는 방법은 브라우저마다 작동을 하지 않을 수 있다. 좀 더 찾아보니 css로 인쇄되는 영역을 제어를 해줄 수 있다.  @media print 를 이용하면 된다. < html > < head > < title > print test page < / title > < style > @media print { . np { display : none ; } } < / style > < / head > < body > < div class = "np" > test < / div > < div > test1 < / div > < div > test1 < / div > < div > test1 < / div > < / body > < / html > 위 코드를 보면 np 클래스를 @media print에 넣어주었다. @media print는 인쇄됐을 때의 스타일을 지정을 해주는 것이다.  위에서는 해당 페이지를 인쇄할 때 p를 display : none으로 가려주었다. @media print를 이용하면 좀 더 멋진 인쇄물을 만들 수 ...

[알고리즘] snake게임 알고리즘

막무가네로 알고리즘을 공부하면 재미가 없으니 게임을 접목하여 다루어 보도록 하겠습니다. 게임의 대상은 스네이크 게임입니다. 많은 사람들은 어릴 때 뱀게임을 많이 해봤을 것 입니다. 이번에 다뤄볼 주제는 뱀이 움직임을 어떻게 구현을 할지 알아보겠습니다. 뱀은 크게 3가지의 경우가 있습니다 1. 가장 중요한 뱀을 움직이기 2. 음식먹기 이때 뱀은 크기가 늘어나야 합니다. 3. 뱀이 움직이는 정책   - 뱀이 움직이지 못하는 경우는 : 우측방향에서 좌측 방향으로 OR 위에 아래 방향고 같이 180도 반전되는 움직임은 막겠습니다. 순수한 알고리즘을 만드는 과정이기 때문에 음식을 먹었는지 안먹었는지 판단하는 부분은 랜덤으로 판단을 하도록 하겠습니다. def is_eat(): return random.choice([1, 0]) 랜덤으로 1, 0을 반환을 해줍니다. 실제로 게임을 만든다면 해당 함수는 뱀의 머리가 음식의 좌표와 같은지 검사를 해주면 되겠습니다. key_position_map = { 'w': [-1, 0], # up 's': [1, 0], # down 'a': [0, -1], # left 'd': [0, 1] # right } direction = key_position_map.get('d') 다음으로는 키맵핑을 한 오브젝트 입니다. direction은 현재 뱀의 방향을 나타냅니다. snake_body = [[2, 3], [1, 3],[1, 2], [1, 1]] 주인공이 되는 뱀의 좌표들 입니다. while True: key = input() new_direction = key_position_map.get(key) if new_direction and direction_check(direction, new_direction): directi...