2015/12/18

[Express.js] 게시판 만들기 예제


generator로 생성되는 기본 view engine은 jade인데,
익숙해 지면 간편할듯 하지만 바로 적응하면서 쓰기엔 시간이 더 걸릴것 같다.

jsp와 비슷한 문법의 ejs도 옵션으로 있으니 이걸 사용한다.
$ express --ejs board

역시 폴더로 이동해서 dependencies를 설치한다.
$ cd board
$ npm install

정상 구동 확인
$ npm start
http://localhost:3000/



테이블 생성
CREATE TABLE `board` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `title` varchar(255) NOT NULL,
   `description` text NOT NULL,
   `img_url` varchar(255) DEFAULT NULL,
   `created` datetime DEFAULT NULL,
   `modifed` datetime DEFAULT NULL,
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4

테스트 데이터 삽입
INSERT INTO board (title, description, created) 
VALUES ('테스트1', '본문 내용', sysdate())
   , ('테스트2', '본문 내용', sysdate())
   , ('테스트3', '본문 내용', sysdate());


MySQL 모듈 설치
$ npm install mysql

개발중 소스 수정시마다 서버 재시작하려면 불편하니 nodemon을 이용한다.
(http://nodemon.io/)
$ npm install -g nodemon

이후 서버 구동은
$ nodemon



app.js에 routes를 추가한다.
...
app.use('/user', users);
// board route 추가
app.use('/board', require('./routes/board')); 
...

routes 폴더에 board.js를 생성한다 (users.js를 복사해서 필요부분을 수정한다.)

var express = require('express');
var router = express.Router();

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'express',
  password : '1234',
  database : 'express'
});

router.get('/', function(req, res, next) {
 connection.query('SELECT * FROM board', function(err, rows, fields) {
   if (err) throw err;
   res.send(rows);
 });

});

module.exports = router;



접속확인
http://localhost:3000/board


이제 view를 입히자.
board.js 수정
...
   //res.send(rows);
   res.render('board/index', { rows: rows });
...


view 폴더에 board 폴더를 만들고 index.ejs를 생성한다.

<!DOCTYPE html>
<html>
  <head>
    <title>test board</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
   <table border="1px">
    <tr>
      <th width="30px">id</th>
      <th width="100px">제목</th>
    </tr>
    <% for(var i=0; i<rows.length; i++) {%>
    <tr>
     <td><%= rows[i].id %></td>
     <td><%= rows[i].title %></td>
    </tr>
    <% } %>
  <table>
  </body>
</html>


접속확인
http://localhost:3000/board


DB 접속과 view 적용이 확인 되었으니 이걸 활용해서 추가/수정/삭제를 구현해보자.



[Express.js] Express application generator

Express application generator

(http://expressjs.com/en/starter/generator.html)을 간단히 번역함.


express-generator 를 사용하면 웹 앱의 구조를 쉽게 잡을 수 있다.

npm 명령어로 간단하게 설치가 가능하다.
$ npm install express-generator -g

실행도 간단하다. myapp이란 이름으로 만들고 싶다면
$ express myapp

기본 파일들과 package.json가 생성되었다.
아래 명령어로 구동에 필요한 dependencies를 설치한다.
$ cd myapp
$ npm install

이제 앱을 실행한다.
디버그 없이 하려면 npm start만 입력해도 된다.
> set DEBUG=myapp:* & npm start

*MacOS나 Linux의 경우 set을 빼고 입력한다.
$ DEBUG=myapp:* npm start


이제 브라우저로 접속해본다.
http://localhost:3000/


생성된 폴더 구조
.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.jade
    ├── index.jade
    └── layout.jade























2015/12/16

[Express.js] Node.js, Express.js 설치



환경 : 
- Windows 7
- OS X 10.10 (Yosemite)



1. Node.js 설치

(https://nodejs.org/en/)
- v4.2.3
msi (맥은 pkg) 실행 후 별다른 변경 없이 'Next'만 눌러도 설치 완료

*이후 윈도우에서 node나 npm 관련 커맨드 사용하려면
시작>모든 프로그램>Node.js>Node.js command prompt를 실행해서 사용


2. Express 설치

(http://expressjs.com/en/starter/installing.html)

- 앱에 사용할 폴더를 만들고 안으로 이동
$ mkdir myapp
$ cd myapp


- 패키지 의존성 관리등에 사용할 package.json 파일 생성
- 아래 명령어를 입력하면 문답형식으로 쉽게 생성할 수 있도록 해준다.
(기본값으로 하려면 엔터만 연타해도 된다)
$ npm init

- 아래 명령어로 package.json 파일의 dependencies에 express를 추가하고 설치한다.
$ npm install express --save



3. Hello world example

(http://expressjs.com/en/starter/hello-world.html)

- 폴더에 아래 내용으로 app.js 파일을 생성

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

- 앱 실행
$ node app.js


- 브라우저로 접속 해서 Hello World! 출력 확인
http://localhost:3000/











2015/09/03

[Javascript] string byte length









 // 최대 바이트 제한
function fnMaxByte(e, max) {
    var $target = $(e.target);  
    var byteCount = getByteLength($target.val());  
    if (byteCount > max) {
        var rtnStr = $target.val();      
        var rtnByte = getByteLength(rtnStr);
        var leng = rtnStr.length;
        while (rtnByte > max) {
            rtnStr = rtnStr.substr(0, leng--);
            rtnByte = getByteLength(rtnStr);
        }
        $target.val(rtnStr);
    } else {
        $($target.closest('div.row')).find('.limitTextNum span').text(byteCount);    }
}


// 바이트 카운트
function getByteLength(s,b,i,c){
    for(b=i=0;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
    return b;
}








2015/07/06

[Javascript] milliseconds to time string




function fnMsToTime(duration) {
    var milliseconds = parseInt((duration%1000)/100)
        , seconds = parseInt((duration/1000)%60)
        , minutes = parseInt((duration/(1000*60))%60)
        , hours = parseInt((duration/(1000*60*60))%24)
        , days = parseInt(duration/(1000*60*60*24));
    hours = (hours < 10) ? "0" + hours : hours;    minutes = (minutes < 10) ? "0" + minutes : minutes;    seconds = (seconds < 10) ? "0" + seconds : seconds;
    return days + "일 " + hours + "시간 " + minutes + "분 " + seconds + "초 " + milliseconds + ' 남음';}






2015/07/01

[cakephp] .htaccess mod_rewrite edit for exclude folder or url


I making cakephp 3.0 web app.

I want to cakephp exclude url for static html folder.


/app/webroot/exclude/some.html


/app/.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine on    RewriteRule    ^$    webroot/    [L]    RewriteRule    (.*) webroot/$1    [L]</IfModule>

webroot/.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On    RewriteCond %{REQUEST_URI} !^/exclude/(.*) # add this Line on default    RewriteCond %{REQUEST_FILENAME} !-f    RewriteRule ^ index.php [L]</IfModule>



http://stackoverflow.com/questions/2249885/cakephp-htaccess-mod-rewrite-configuration-to-exclude-a-particular-folder-url

2015/06/24

[php] increase max upload size (wordpress)




PHP_INI_PERDIR Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3)

php.ini

upload_max_filesize = 32M
post_max_size = 32M

then httpd restart




http://stackoverflow.com/questions/13442270/ini-setupload-max-filesize-200m-not-working-in-php

[apache] change run user, group

cakephp3 Permission denied error




/etc/apache2/envvars

# Since there is no sane way to get the parsed apache2 config in scripts, some
# settings are defined via environment variables and then used in apache2ctl,
# /etc/init.d/apache2, /etc/logrotate.d/apache2, etc.

##export APACHE_RUN_USER=www-data
##export APACHE_RUN_GROUP=www-data
## 아파치 유저 변경
export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data


service apache restart







[cakephp] not found the requested url (apache)



/etc/apache2/sites-available/default


<Directory />
    Options FollowSymLinks
    AllowOverride All
</Directory>
<Directory /var/www>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order Allow,Deny
    Allow from all
</Directory>



http://book.cakephp.org/3.0/en/installation.html#url-rewriting



[vagrant] synced folder owner change (apache)




vagrant file edit

## 공유 폴더 권한 변경

#config.vm.synced_folder "./source", "/var/www/source", create: true
config.vm.synced_folder "./source", "/var/www/source", create: true,
      :owner => "vagrant",
      :group => "www-data",
      :mount_options => ["dmode=775","fmode=664"]



$ vagrant reload