nodejs - form submit

시스템 2019. 1. 22. 11:33

새로고침 없는 비동기로 새로운 방식이라고 한다.

 

 

nodejs - form submit

 

app.js


const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));

app.get('/', (req, res) => {
    res.sendfile('public/index.html');
});

app.post('/login', (req, res) => {
        console.log(req.body.userId, req.body.userPw);
    if(req.body.userId==='admin'&&req.body.userPw==='1234'){
        res.json({success:true});
    }else{
        res.json({success:false});
    }
});

app.listen(8000);

console.log("open 8000");


module.exports = app;


 

 

public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="//code.jquery.com/jquery-latest.min.js"></script>
    <title>Hello</title>
    <script>
        $(document).ready(function (){
            $('#login').click(function () {
                $.ajax({
                    url: 'http://192.168.0.118:8000/login',
                    method : 'POST',
                    data: {userId : $('#id').val(), userPw: $('#pw').val()},
                    dataType: 'json'
                }).done(function(data){
                    if(data.success)
                        alert('로그인 성공');
                    else
                        alert('로그인 실패');
                }).fail(function (data){
                    alert('로그인 오류');
                })
            });
        });
    </script>
</head>
<body>
    <h1>로그인페이지</h1>
    <hr>
    아이디 <input type="text" id='id'>
    패스워드 <input type="password" id='pw'>
    <button id="login">로그인</button>

</body>
</html>

 

실행 결과

 

미들웨어 처리 함

root@tkpark-VirtualBox:~/project/myapp# yarn start
yarn run v1.13.0
$ node ./bin/www
open 8000
admin 1234
admin 1
admin 1
admin 1234
admin 1234

 

 

http://192.168.0.118:8000/

이제 기존의 route랑 연동해야겠다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'시스템' 카테고리의 다른 글

시놀리지 나스 synology nas(redmine plugin)설치  (2) 2019.04.29
pm2  (0) 2019.03.28
nodejs + mariadb 연동  (0) 2019.01.14
nodejs json파일 MongDB에 입력  (0) 2018.12.04
nodejs json파일 컨트롤  (0) 2018.12.04
블로그 이미지

iesay

,