반응형
Installation
$ npm install cookie-parser

API

var express      = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

cookieParser(secret, options)

  • secret a string used for signing cookies. This is optional and if not specified, will not parse signed cookies.
  • options an object that is passed to cookie.parse as the second option. See cookie for more information.
    • decode a function to decode the value of the cookie

cookieParser.JSONCookie(str)

Parse a cookie value as a JSON cookie. This will return the parsed JSON value if it was a JSON cookie, otherwise it will return the passed value.

cookieParser.JSONCookies(cookies)

Given an object, this will iterate over the keys and call JSONCookie on each value. This will return the same object passed in.

cookieParser.signedCookie(str, secret)

Parse a cookie value as a signed cookie. This will return the parsed unsigned value if it was a signed cookie and the signature was valid, otherwise it will return the passed value.

cookieParser.signedCookies(cookies, secret)

Given an object, this will iterate over the keys and check if any value is a signed cookie. If it is a signed cookie and the signature is valid, the key will be deleted from the object and added to the new object that is returned.

Example

var express      = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function(req, res) {
  console.log("Cookies: ", req.cookies)
})

app.listen(8080)

// curl command that sends an HTTP request with two cookies
// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello"

 

반응형
반응형

 

 

http://stackoverflow.com/questions/4482686/check-synchronously-if-file-directory-exists-in-node-js

반응형
반응형
Server.js
/*Define dependencies.*/

var express=require("express");
var multer  = require('multer');
var app=express();
var done=false;

/*Configure the multer.*/

app.use(multer({ dest: './uploads/',
 rename: function (fieldname, filename) {
    return filename+Date.now();
  },
onFileUploadStart: function (file) {
  console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
  console.log(file.fieldname + ' uploaded to  ' + file.path)
  done=true;
}
}));

/*Handling routes.*/

app.get('/',function(req,res){
      res.sendfile("index.html");
});

app.post('/api/photo',function(req,res){
  if(done==true){
    console.log(req.files);
    res.end("File uploaded.");
  }
});

/*Run the server.*/
app.listen(3000,function(){
    console.log("Working on port 3000");
});
index.html
<form id        =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/photo"
     method    =  "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>

 

 

https://codeforgeek.com/2014/11/file-uploads-using-node-js/

반응형
반응형

 

 

http://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4

 

express/connect top-level generic

This example demonstrates adding a generic JSON and URL-encoded parser as a top-level middleware, which will parse the bodies of all incoming requests. This is the simplest setup.

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

express route-specific

This example demonstrates adding body parsers specifically to the routes that need them. In general, this is the most recommend way to use body-parser with express.

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  res.send('welcome, ' + req.body.username)
})

// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  // create user in req.body
})

change content-type for parsers

All the parsers accept a type option which allows you to change the Content-Type that the middleware will parse.

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))
반응형
반응형

 

 

위 오류가 날때...

 

 

 

app.router 를 use 하는 라인을 지워주면 된다.

예전에는 넣어줘야되는데 최신버젼에선 없어졌다고 한다.

반응형
반응형

- Project Explorer 뷰 - Project 선택 - Properties

- Web Project Settings - Context root 를 / 로 변경

- 메뉴 - Project - Clean

- Servers 뷰에서 tomcat 선택, + 펼침, 해당 프로젝트 선택 후 삭제

- Servers 뷰에서 tomcat 선택 - 마우스 우클릭, Clean

- Servers 뷰에서 tomcat 선택 - 마우스 우클릭, Add and Remove

- 해당 프로젝트 선택후 Add

반응형
반응형

iBook 에서 이미지를 클릭 했을때 동적으로 div를 생성하고 그 안에 background-image 스타일 지정을 해주었으나 도통 빈 칸만 뜨고 이미지가 출력되지 않았다.

 

콘솔로그를 찍어볼 수 없는 거지같은 테스트환경이어서 html 마크업으로 일일히 확인해본 결과 이미지를 불러올때 ibooksimg:// 라는 프로토콜을 사용해야 하지만 ibooks:// 로 불러오면서 이미지가 출력되지 않은 것이었다.

 

var str = $("img").get(0).src;

str = str.replace("ibooks://", "ibooksimg://");

 

로 간단히 replace 치환처리 하니 정상 출력되었다.

반응형
반응형

이미지의 원본 크기를 구하기 위해서 $("img").get(0).naturalWidth 이나 naturalHeight 를 변수에 초기화했을때, 0 값이 떨어진다. 이러한 현상을 막기 위해서

 

$("img").load(function(){

var img = {
  width:$(this).get(0).naturalWidth,

  height:$(this).get(0).naturalHeight

});

 

등으로 사용할 수 있다. 그런데 여기서 load 된 값이 캐슁처리되면서 더이상 load가 실행되지 않는다.

이때 아래와 같은 방법으로 대응가능하다.

 

$("img").one("load",function(){

var img = {
  width:$(this).get(0).naturalWidth,

  height:$(this).get(0).naturalHeight

}).each(function(){

if(this.complete){

$(this).trigger("load");

}

});

 

예를 들어 문서가 로드된 상태에서 이미지 목록이 갱신 되었을 때 해당 목록에 있는 이미지들의 원본값을 배열에 초기화하고 싶을때 사용될 수 있겠다.

반응형

'웹프로그래밍 > Javascript' 카테고리의 다른 글

지정된 영역만 인쇄하기  (0) 2015.06.15
Javascript iBook EPUB 3.0 Images not working  (0) 2015.05.27
jQuery Animation Rotate  (0) 2015.05.06
Javascript 모바일 체크  (0) 2015.04.23
Javascript Favicon 적용  (0) 2015.04.23

+ Recent posts