Node.Js 세션, 라우터 기능 예시
user.js
1
2
3
4
5
6
7
8
9
|
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Heelo, User');
});
module.exports = router;
|
cs |
index.js
1
2
3
4
5
6
7
8
9
|
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Heelo, User');
});
module.exports = router;
|
cs |
app.js
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
66
67
68
|
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const indexRouter = require('./routes');
const userRouter = require('./routes/user');
const app = express();
app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(cookieParser('zerocho'));
app.use(session({
resave : false,
saveUninitialized : false,
secret : 'shinpassword',
cookie: {
httpOnly : true,
},
name : 'connect.sid',
}));
app.use('/',(req, res, next) =>{
if(req.session.id){
express.static(path.join(__dirname, 'public'))(req, res, next)
}else{
next;
}
});
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use('/', indexRouter);
app.use('/user', userRouter);
app.get('/', (req, res, next) =>{
req.session.id ='hello';
//res.sendFile(path.join(__dirname,'index.html'));
res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/', (req, res) =>{
res.send('hello express');
});
app.get('/category/:name', (req, res) =>{
res.send(`hello ${req.params.name}`);
});
app.get('/about', (req, res) =>{
res.send('about1');
});
app.use((req, res, next)=>{
res.status(404).send('404에러');
});
app.use((err, req, res, next)=>{
console.error(err);
res.send('에러발생');
});
app.listen(3000, ()=>{
console.log('익스프레스 서버 실행');
});
|
cs |
'개발 > Node.js' 카테고리의 다른 글
[Node.js] Work-Thread 예시 (0) | 2023.05.13 |
---|---|
[Node.js] npm WARN config global --global, --local are deprecated. Use --location=global instead. 에러 해결 (1) | 2023.05.13 |