• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

이미지 업로드 안되는 문제

24.01.22 16:11 작성 24.01.22 16:23 수정 조회수 172

0

선생님 안녕하세요


도메인 대신 탄력적 ip2개를 front, back인스턴스에 연결해서 사용중인데요, 로그인이 되지 않았습니다.라는 메세지가 뜨며 이미지 업로드가 안되서 안되 상황입니다. isAuthenticated가 false가 되는 원인을 알고 이 문제를 해결하고 싶어 문의드립니다.

사용중인 ip)
back
13.209.144.99

front

13.125.122.77

스크린샷 2024-01-22 오후 4.12.07.png


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

스크린샷 2024-01-22 오후 4.21.49.png스크린샷 2024-01-22 오후 4.21.42.png
스크린샷 2024-01-22 오후 3.06.20.png스크린샷 2024-01-22 오후 3.26.39.png스크린샷 2024-01-22 오후 3.26.59.png스크린샷 2024-01-22 오후 3.27.22.pngerrorlog 전체)
스크린샷 2024-01-22 오후 4.05.52.png스크린샷 2024-01-22 오후 4.06.03.png스크린샷 2024-01-22 오후 4.06.15.png스크린샷 2024-01-22 오후 4.06.22.png
에러로그 일부)

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에 이미지 업로드 실패
스크린샷 2024-01-22 오후 3.09.09.png

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

·

답변을 작성해보세요.

1

아마 쿠키 문제일 것입니다. 도메인이 아니라 ip로 하는 경우 프론트와 백엔드간에 쿠키가 공유가 되지 않습니다. 도메인을 넣으셔야 합니다.

0

박해진님의 프로필

박해진

질문자

2024.01.22

아항 감사합니당 선생님!!