반응형

get 방식


특정 경로에 있는 폴더(public 폴더)를 요청에 의해서 바로 파일을 가져올 수 있는 기능을 제공 해주는 모듈 "serve-static" 이라는 것이 존재






우선 프로젝트 폴더에 public 이란 폴더를 만들어 놓는다


public 폴더안에 /game0.jpg 가 있는 상태라 가정




이럴 경우 서버를 실행 시킨다음에 브라우저에서


http://localhost:3000/game0.jpg 를 입력하면 해당 이미지가 열리는 것을 알 수 있다



만약  public/image/game0.jpg 로 배치해 놓았다면


http://localhost:3000/image/game0.jpg  로 입혁하면 된다



또는 서버에서 


res.end("<img src='/game0.jpg' ");


를 입력하여 곧바로 이미지를 보낼 수 있다





소스코드 : 


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
38
39
40
41
42
43
44
45
46
47
48
49
var express = require('express');
var http = require('http');
var serveStatic = require('serve-static');      //특정 폴더의 파일들을 특정 패스로 접근할 수 있도록 열어주는 역할
var path = require('path');
 
var app = express();      //express 서버 객체
 
app.set('port'3000);
 
//join은 __dirname : 현재 .js 파일의 path 와 public 을 합친다
//이렇게 경로를 세팅하면 public 폴더 안에 있는것을 곧바로 쓸 수 있게된다
app.use(serveStatic(path.join(__dirname, 'public')));
 
 
///users 를 붙이게 되면 특정 경로를 지정하는 것으로 특정 기능을 수행할떄 사용한다
//localhost:3000/users
//example , get 방식
//localhost:3000/users?name=tesstsssssss
 
app.use(
    function (req, res, next) {
        console.log('middle wared was called : first');
        //res.redirect('http://google.co.kr');
 
        //req 여러 정보를 얻어 올 수 있는데 그중
        //요청받은 request 정보중에서 User-Agent 정볼를 따로 분리하여 갖어올 수 있다
        var userAgent = req.header('User-Agent');
 
        //요청파라미터는 get 방식인 req.query 에 들어오게 된다
        //post 방식은 body로 들어오게된다
        //name 은 정해져있는 명칭
        var paramName = req.query.name;
 
        //응답 보내기
        res.send('<h3>response from server!!!!!!!!!!!! : ' + userAgent + '</h3>' + paramName);
 
    }
);
 
 
//웹서버를 app 기반으로 생성
var appServer = http.createServer(app);
appServer.listen(app.get('port'),
    function () {
        console.log('express 웹서버 실행' + app.get('port'));
    }
 
);
 






결과 : 



http://localhost:3000/game0.jpg



인사이드 inside








post 방식

npm install body-parser --save 이 모듈을 설치해야한다



위으 소스에서 세군대 정도만 변경 또는 추가가 되는데 주의할 점은 일반 브라우저에서는 post 방식으로 보내면 안된다

주소 뒤에 ?name='sdf'  추가 하는 방식은 get 방식이기 때문에 이렇게 보내면 안되고

body 라는 곳에 추가를 해야 하는데 이것은 postman 이라는 툴을 사용해서 post 방식으로 보다 쉽게 보내는 방식이 존재한다


postman 을 설치하고 다음 처럼 입력하면 결과를 볼 수 있다

postman 으로 param 을 선택한다음 name, 과 출력할 값을 넣어주면 기존 get 방식과 거의 동일한 실행흐름이 진행된다는 것을 알 수 있다




소스코드 :


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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var express = require('express');
var http = require('http');
var serveStatic = require('serve-static');      //특정 폴더의 파일들을 특정 패스로 접근할 수 있도록 열어주는 역할
var path = require('path');
 
var app = express();      //express 서버 객체
//post 방식 일경우 begin
var bodyParser_post = require('body-parser');       //post 방식 파서
//post 방식 일경우 end
app.set('port'3000);
 
//join은 __dirname : 현재 .js 파일의 path 와 public 을 합친다
//이렇게 경로를 세팅하면 public 폴더 안에 있는것을 곧바로 쓸 수 있게된다
app.use(serveStatic(path.join(__dirname, 'public')));
 
 
//post 방식 일경우 begin
//post 의 방식은 url 에 추가하는 방식이 아니고 body 라는 곳에 추가하여 전송하는 방식
app.use(bodyParser_post.urlencoded({ extended:false }));            // post 방식 세팅
app.use(bodyParser_post.json());                                     // json 사용 하는 경우의 세팅
//post 방식 일경우 end
 
 
///users 를 붙이게 되면 특정 경로를 지정하는 것으로 특정 기능을 수행할떄 사용한다
//localhost:3000/users
//example , get 방식
//localhost:3000/users?name=tesstsssssss
 
app.use(
    function (req, res, next) {
        console.log('middle wared was called : first');
        //res.redirect('http://google.co.kr');
 
        //req 여러 정보를 얻어 올 수 있는데 그중
        //요청받은 request 정보중에서 User-Agent 정볼를 따로 분리하여 갖어올 수 있다
        var userAgent = req.header('User-Agent');
 
        //요청파라미터는 get 방식인 req.query 에 들어오게 된다
        //post 방식은 body로 들어오게된다
        //name 은 정해져있는 명칭
        //var paramName = req.query.name;           //get 방식
 
//post 방식 일경우 begin
        var paramName = req.body.name;           //post 방식 //post 방식 일경우 end
 
        //post, get 방식 동시에 되는 것 얻기, || 연산자는 둘중에 null 또는 undefined 가 아닌 것을 리턴한다
        //var paramName = req.query.name || req.body.name;
 
        //응답 보내기
        res.send('<h3>response from server!!7!! : ' + userAgent + '[' + paramName  + '] </h3>');
 
    }
);
 
 
//웹서버를 app 기반으로 생성
var appServer = http.createServer(app);
appServer.listen(app.get('port'),
    function () {
        console.log('express 웹서버 실행' + app.get('port'));
    }
 
);
 




Postman 으로 입력하는 모습


  1. Post 옆에 url은 localhost:3000 까지만 입력하고 옆에 Params 를 눌러 파라미터를 입력한다
  2. Body 클릭
  3. "x-www-form-urlencoded" 를 클릭한다음 key, value 에 전송할 데이터를 입력


결과는 이미지 하단에 나타남










반응형

+ Recent posts