'body-parser'에 해당되는 글 1건

  1. 2014.09.18 [nodejs] POST 데이터 받기 express 사용 / 미사용 비교
Programming/node.js2014. 9. 18. 19:14

1. http/ querystring만 사용


  1. var http = require('http')
  2. ,qs = require('querystring');
  3. http.createServer(function (req, res) {
  4. if( req.url == '/' && req.method == 'POST'){
  5. var postBody = '';
  6. req.on('data', function (data) {
  7. postBody += data;
  8. });
  9. req.on('end', function () {
  10. var post = qs.parse(postBody);
  11. //post데이터확인
  12. console.log(post['postname']);
  13. });
  14. res.end('true');
  15. }else{
  16. res.writeHead(404, {'Content-Type': 'text/plain'});
  17. res.end('404 ERROR');
  18. }
  19. }).listen(8001);


2. http / express  / body-parser 사용


  1. var express = require('express')
  2. ,http = require('http')
  3. ,bodyParser = require('body-parser');
  4. var app = express();
  5. app.use(bodyParser.urlencoded({extended: true}));
  6. //app.use(bodyParser.json());
  7. app.post("/", function( req, res){
  8. res.writeHead(200,{"Content-Type" : "text/plain"});
  9. //post데이터확인
  10. console.log(req.param('postname',null));
  11. res.end('test');
  12. });
  13. app.use(function( req, res){
  14. res.writeHead(404,{"Content-Type" : "text/plain"});
  15. res.end('404 ERROR');
  16. });
  17. http.createServer(app).listen(8001);


Posted by 시니^^