인디노트

AngularJS 와 NodeJS 를 함께 가동하기 본문

개발 플랫폼 및 언어/앵귤러 Algular

AngularJS 와 NodeJS 를 함께 가동하기

인디개발자 2019. 8. 22. 17:48

앵귤러를 이용하여 Ajax 서버를 구현하려면 쉽게 되질 않는다. 오해스럽지만 불가능하다.

앵귤러는 클라이언트 자바스크립트 기반의 프래임워크이기 때문에 당연하다.

따라서 Angular 에  NodeJS 를 함께하여 Ajax 서버쪽을 NodeJS 로 구현하는 방법이 유리하다.

물론 Ajax 서버 쪽을 다른 HTTP 서버를 이용하여 만들어도 되지만 AngularJS 를 기본으로 구성하는 차원에서는 그것도 쉽지 않은 결정이 될 것이다.

이제 AngularJS 와 NodeJS 를 어떻게 구성하면 되는지 설명한다.

우선, AngularJS 에 다음 내용의 파일을 생성한다. 그냥 본인의 Angular 프로젝트 폴더에 생성하면 된다.

파일명 : proxy.config.json
{
     "/api/*":
     {
       "target":"http://localhost:3000",
       "secure":false,
       "logLevel":"debug"
     }
}

파일명 : api.js
const express = require('express')
const app = express()
app.post('/api', function(req, res) {
    //console.log(JSON.stringify(req.body));
    res.status(200).send('whatever you want to send back to angular side');
});
app.get('/api', function(req, res) {
    //console.log(req.params);
    res.status(200).send('whatever you want to send back to angular side');
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))


터미널을 열고 다음과 같이 Node 를 실행한다.
node api.js

다음과 같은 메시지가 표시될 것이다.
Example app listening on port 3000!

이제 다음과 같은 명령으로 Angular 를 실행한다.
ng serve --host 0.0.0.0 --disableHostCheck --open --proxy-config proxy.config.json


실행하는 로그에 다음과 같은 메시지가 표시됨을 확인 할 수 있다.
 10% building 4/4 modules 0 active[HPM] Proxy created: /api  ->  http://localhost:3000
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]
결국 /api  로 들어오는 접속은 3000번포트 즉, NodeJS 로 실행한 app.js 로 연결한다는 의미이다.

여기서 주의해야 할 것은 /api 와 같이 연결하는 패스를 같은것으로 사용해야 한다는 것이다.

Angular 에서 /api 로 연결되는 접속은 http://localhost:3000 으로 연결하는데 이떄도 /api 를 사용하기 때문에 NodeJS 에도 해당 매핑이 필요한 것이다.

이제 http://localhost:4200/api 를 접속해 보자.

웹브라우저에 
whatever you want to send back to angular side
라고 표시됨을 알 수 있을 것이다.

이제 이렇게되면 AngularJS 와 NodeJS 를 함깨 사용하는 서버가 구성되는데...

만약, 구글의 Firebase hosting 서버를 사용한다면 이에 적용하기 위해서 NodeJS 의 처리가 어떻게 되는지 확인이 필요할 것이다.

반응형
Comments