티스토리 뷰
페이지를 벗어날 때 어떤 이벤트를 실행시킬 때, navigator.sendBeacon() 메서드를 사용하면된다.
window.addEventListener("unload", () => {
let dummy = new FormData();
dummy.append('data','xxxxxxxxx');
window.navigator.sendBeacon("http://localhost:3000/chat/end",dummy);
}, false);
이 메서드를 사용해서 페이지를 나가기 전에 서버로 작은 데이터를 보내주고 싶었다.
window.navigator.sendBeacon("경로",데이터);
데이터를 폼객체에 담아서 보내줬다.
페이지를 나가면
샌드비콘은
router.post('/end',controller.end);
이 라우터를 타고 들어가서,
let end = (req,res)=>{
console.log(req);
}
여기 도착해서 req 내용을 콘솔창에 뿌려주는데
이렇게 따라하면 req에 쓸데없는 내용만 잔뜩 나온다. 이유는 다음과 같다.
req에 찍힌 내용의 일부
//////////////////////////////////////////////////////////////////////////
" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'sec-ch-ua-mobile',
'?0',
'User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/91.0.4472.114 Safari/537.36',
'Content-Type',
'multipart/form-data; boundary=----WebKitFormBoundaryKjnUSyIQG9KNAjTl',
'Accept',
'*/*',
'Origin',
'http://localhost:3000',
'Sec-Fetch-Site',
'same-origin',
'Sec-Fetch-Mode',
////////////////////////////////////////////////////////////////////
위에 보면 Content-Type 이 multipart/form-data; 이다.
const multer = require('multer'); //npm install multer
const upload = multer({
storage:multer.diskStorage({
destination:function(req,file,callback){
callback(null,'uploads')//폴더명
},
filename:function(req,file,callback){
callback(null,new Date().valueOf()+ path.extname(file.originalname))
} //path.extname(file.originalname)): 확장자 가져오는 코드
}),
})
router.post('/end', upload.single('data'),controller.end);
multer 멀터를 추가해주고. 경로에 미들웨어 추가해주면 된다.
그러면
sessionID: 'Y_Y4ZWpngfoV8ClzOydciDVmKOS4WLor',
session: Session {
cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
},
////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
body: [Object: null prototype] { data: 'xxxxxxxxx' },
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
secret: undefined,
cookies: [Object: null prototype] {},
signedCookies: [Object: null prototype] {},
route: Route {
path: '/end',
stack: [ [Layer], [Layer] ],
methods: { post: true }
},
__onFinished: null,
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
}
body에 아까 보낸 데이터가 잘 들어있는 것을 볼 수 있다,
728x90
'Node.js' 카테고리의 다른 글
socket.io 이벤트 (0) | 2021.07.04 |
---|---|
socket.io 시작 (0) | 2021.07.04 |
게시판 테이블. (0) | 2021.06.09 |
0527 수업내용. (0) | 2021.05.27 |
카카오 로그인 맛보기 (0) | 2021.05.21 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- node.js
- 다이나밍프로그래밍
- 서버점검
- 롱베케이션
- 다이나믹프로그래밍
- create db
- 로드나인
- 서버개발
- 면접비
- 개발자면접
- MySQL
- 동적프로그래밍
- 투포인터 연습
- 투포인터
- DB 생성
- MOD
- 은둔청년체험
- 그래프
- create databases;
- 면접질문
- BFS
- 최소공통조상
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함