이미지 업로드 안되는 문제
430
投稿した質問数 12
선생님 안녕하세요
도메인 대신 탄력적 ip2개를 front, back인스턴스에 연결해서 사용중인데요, 로그인이 되지 않았습니다.라는 메세지가 뜨며 이미지 업로드가 안되서 안되 상황입니다. isAuthenticated가 false가 되는 원인을 알고 이 문제를 해결하고 싶어 문의드립니다.
사용중인 ip)
back
13.209.144.99
front
13.125.122.77

현재 화면)
monit에 uploadImages관련 상태 결과 false





errorlog 전체)



에러로그 일부)
0|npm | cause: Error: socket hang up
0|npm | at connResetException (node:internal/errors:787:14)
0|npm | at Socket.socketOnEnd (node:_http_client:519:23)
0|npm | at Socket.emit (node:events:530:35)
0|npm | at endReadableNT (node:internal/streams/readable:1696:12)
0|npm | at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
0|npm | code: 'ECONNRESET'
0|npm | }
0|npm | }
0|npm | TypeError: Cannot read properties of undefined (reading 'data')
0|npm | at loadMyInfo (/home/ubuntu/react_nodebird/front/.next/server/pages/_app.js:531:27)
0|npm | at loadMyInfo.throw (<anonymous>)
0|npm | at next (/home/ubuntu/react_nodebird/front/node_modules/@redux-saga/core/dist/redux-saga-core.prod.cjs.js:1070:32)
0|npm | at currCb (/home/ubuntu/react_nodebird/front/node_modules/@redux-saga/core/dist/redux-saga-core.prod.cjs.js:1195:7)
0|npm | at /home/ubuntu/react_nodebird/front/node_modules/@redux-saga/core/dist/redux-saga-core.prod.cjs.js:346:5
0|npm | at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
0|npm | The above error occurred in task loadMyInfo
0|npm | created by takeLatest(LOAD_MY_INFO_REQUEST, loadMyInfo)
0|npm | created by watchLoadMyInfo
0|npm | created by userSaga
0|npm | created by rootSaga
0|npm | Tasks cancelled due to error:
0|npm | postSaga
0|npm | TypeError: Cannot read properties of undefined (reading 'data')
0|npm | at loadMyInfo (/home/ubuntu/react_nodebird/front/.next/server/pages/_app.js:531:27)
0|npm | at loadMyInfo.throw (<anonymous>)
0|npm | at next (/home/ubuntu/react_nodebird/front/node_modules/@redux-saga/core/dist/redux-saga-core.prod.cjs.js:1070:32)
0|npm | at currCb (/home/ubuntu/react_nodebird/front/node_modules/@redux-saga/core/dist/redux-saga-core.prod.cjs.js:1195:7)
0|npm | at /home/ubuntu/react_nodebird/front/node_modules/@redux-saga/core/dist/redux-saga-core.prod.cjs.js:346:5
0|npm | at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
질문1)이미지 업로드시 isAuthenticated가 false가 되는 원인이 뭘까요?
질문2)도메인 안쓰고 탄력적 ip 2개 연결해서 쓰면 쿠키가 전달이 안되서 이미지 업로드는 못하나요?
질문3)이 부분에 문제가 있을까요?
if(process.env.NODE_ENV === 'production'){
app.use(morgan('combined'));
app.use(hpp());
app.use(helmet());
app.use(cors({
origin: 'http://13.125.122.77',
credentials: true,
}));
} else {
app.use(morgan('dev'));
}
app.use(cors({
origin: ['http://localhost:3060', 'http://13.125.122.77'],
credentials:true
}));app.use(session({
saveUninitialized: false,
resave: false,
secret: process.env.COOKIE_SECRET,
cookie: {
httpOnly: true, //자바스크립트로 접근하지못하게
secure: false, //일단 false로 하고 https적용할 땐 ture
// domain: process.env.NODE_ENV = 'production' && '.nodebirdcom' //도메인 사용할 경우
},
}));
back/app.js 전체
const express = require('express');
const cors = require('cors');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const passport = require('passport');
const dotenv = require('dotenv');
const morgan = require('morgan');
const postRouter = require('./routes/post');
const postsRouter = require('./routes/posts');
const userRouter = require('./routes/user');
const hashtagRouter = require('./routes/hashtag');
const db = require('./models');
const passportConfig = require('./passport');
const path = require('path');
const hpp = require('hpp');
const helmet = require('helmet');
dotenv.config();
const app = express();
db.sequelize.sync()
.then(() => {
console.log('DB 연결 성공');
}).catch(console.error);
passportConfig();
if(process.env.NODE_ENV === 'production'){
app.use(morgan('combined'));
app.use(hpp());
app.use(helmet());
app.use(cors({
origin: ['http://nodebird.com', 'http://13.125.122.77'],
credentials: true,
}));
} else {
app.use(morgan('dev'));
}
app.use(cors({
origin: ['http://localhost:3060', 'http://nodebird.com', 'http://13.125.122.77'],
credentials:true
}));
app.use('/', express.static(path.join(__dirname, 'uploads')));
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(session({
saveUninitialized: false,
resave: false,
secret: process.env.COOKIE_SECRET,
cookie: {
httpOnly: true, //자바스크립트로 접근하지못하게
secure: false, //일단 false로 하고 https적용할 땐 ture
// domain: process.env.NODE_ENV = 'production' && '.nodebirdcom' //도메인 사용할 경우
},
}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', (req, res) =>{
res.send('hello express');
});
app.use('/posts', postsRouter);
app.use('/post', postRouter);
app.use('/user', userRouter);
app.use('/hashtag', hashtagRouter);
app.listen(80, () => {
console.log('서버 실행 중');
});
routes/post 일부
const express = require('express');
const {Post, Image, Comment, User, Hashtag} = require('../models');
const {isLoggedIn} = require('./middlewares');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const multerS3 = require('multer-s3');
const AWS = require('aws-sdk');
try {
fs.accessSync('uploads');
} catch(error) {
console.error('uploads폴더가 없으므로 생성합니다.');
fs.mkdirSync('uploads');
}
AWS.config.update({
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
region: 'ap-northeast-2',
});
const upload = multer({
storage: multerS3({
s3: new AWS.S3(),
bucket: 'react-saga-nodebird-s3',
key(req, file, cb){
cb(null, `original/${Date.now()}_${path.basename(file.originalname)}`)
}
}),
limits: {fileSize: 20 * 1024 * 1024} //20MB
});
router.post('/images', isLoggedIn, upload.array('image'),(req, res, next) => { //POST /post/images
res.json(req.files.map((v) => v.location));
});
middlewares.js
exports.isLoggedIn = (req, res, next) => {
if(req.isAuthenticated()) {
next();
} else {
res.status(401).send('로그인이 필요합니다.');
}
}
front에 img src에서 backUrl 지워줌
시도해본 것)
cors리소스 공유에 아래 내용을 넣어서 실행해보기도 하고 없는 상태에서도 실행해보았지만 상태코드는 401에 이미지 업로드 실패
back/package.json 일부
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "cross-env NODE_ENV=production pm2 start app.js"
},front/package.json 일부
"scripts": {
"dev": "npx browserslist@latest --update-db && NODE_OPTIONS=--openssl-legacy-provider next -p 3060",
"build": "cross-env ANALYZE=true NODE_ENV=production next build",
"start": "cross-env NODE_ENV=production next start -p 80",
"lint": "eslint ."
},
回答 2
넥스트 버젼 질문
0
77
2
로그인시 401 Unauthorized 오류가 뜹니다
0
89
1
무한 스크롤 중 스크롤 튐 현상
0
174
1
특정 페이지 접근을 막고 싶을 때
0
103
2
createGlobalStyle의 위치와 영향범위
0
96
2
인라인 스타일 리렌더링 관련
0
91
2
vsc 에서 npm init 설치시 오류
0
146
2
nextjs 15버전 사용 가능할까요?
0
158
1
화면 새로고침 문의
0
121
1
RTK에서 draft, state 차이가 있나요?
0
153
2
Next 14 사용해도 될까요?
0
452
1
next, node 버전 / 폴더 구조 질문 드립니다.
0
349
1
url 오류 질문있습니다
0
211
1
ssh xxxxx로 우분투에 들어가려니까 port 22: Connection timed out
0
372
1
sudo certbot --nginx 에러
0
1272
2
Minified React error 콘솔에러 (hydrate)
0
469
1
카카오 공유했을 때 이전에 작성했던 글이 나오는 버그
0
247
1
프론트서버 배포 후 EADDRINUSE에러 발생
0
325
1
npm run build 에러
0
518
1
front 서버 npm run build 중에 발생한 에러들
0
381
1
서버 실행하고 브라우저로 들어갔을때 404에러
0
337
2
css 서버사이드 랜더링이 적용되지 않아서 문의 드립니다.
0
286
1
팔로워 3명씩 불러오고 데이터 합쳐주는걸로 바꾸고 서버요청을 무한으로하고있습니다.
0
237
2
해시태그 검색에서 throttle에 관해 질문있습니다.
0
201
1

