multer 이미지 업로드 오류 질문드립니다
619
작성한 질문수 2
드롭존을 사용하여 이미지 업로드를 했을때,
서버 단에서
TypeError: Cannot read properties of undefined (reading 'path')
라는 에러 메시지와 함께 업로드가 완료되지 않는 문제가 발생했습니다.
클라이언트 단에서는
POST http://localhost:3000/api/products/image 500 (Internal Server Error)
라는 500 서버 에러가 발생했다고 나왔었구요
한가지 의문인 것은,
여러 방법을 시도해보다가
FileUpload 유틸에서 axios headers config를 삭제하고 시도하니 제대로 잘 동작을 하였습니다..
유추해보건데, 다른 코드들은 잘 작성되어 동작하지만 해당 config 부분에서 문제가 생긴 것 같습니다, 그렇다면 이유가 무엇인지 궁금합니다
FileUpload.js
import React from "react";
import Dropzone from "react-dropzone";
import axios from "axios";
const FileUpload = () => {
const dropHandler = (files) => {
// console.log("dropped file", files); // 파일은 잘 들어옴
console.log(files);
let formData = new FormData();
// const config = {
// headers: { "content-type": "multipart/form-data" },
// };
formData.append("file", files[0]);
// axios.post("/api/products/image", formData, config).then((res) => {
axios.post("/api/products/image", formData).then((res) => {
if (res.data.success) {
console.log(res.data);
} else {
alert("파일을 저장하는데 실패하였습니다");
}
});
};
return (
<Dropzone onDrop={dropHandler}>
{({ getRootProps, getInputProps }) => (
<section>
<div
style={{
width: "400px",
height: "400px",
backgroundColor: "white",
border: "1px solid lightgray",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
{...getRootProps()}
>
<input {...getInputProps()} />
<p style={{ fontSize: "5rem" }}>+</p>
</div>
</section>
)}
</Dropzone>
);
};
export default FileUpload;
products.js (강의와 다르게 product"s"로 바꾸고 관련 코드들도 수정하였었습니다)
const express = require("express");
const router = express.Router();
const multer = require("multer");
//=================================
// Product
//=================================
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
}, // 파일이 어디에 저장이 되는가에 대한 부분
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({ storage: storage }).single("file");
router.post("/image", (req, res) => {
console.log(storage.filename);
upload(req, res, (err) => {
if (err) {
return res.json({ success: false, err });
}
return res.json({
success: true,
filePath: res.req.file.path,
fileName: res.req.file.filename,
});
});
});
module.exports = router;
답변 0
강의 내용은 훌륭하나, 환경 설정 오류 때문에 진도를 나갈 수 없습니다. 20년 버전 강의.
0
61
1
강의자료는 어디서 볼 수있나요??
0
68
1
이 쇼핑몰 만들기 강의는 관리자페이지 만드는건 없나요
0
120
2
웹에서 실시간 코드반영이 안돼요
0
124
1
app.use질문
0
66
1
강사님께 어떻게 직접질문할수있어요??
0
77
1
const함수같은거 기초강의는 어디있나요
0
85
2
리덕스 참조챕터가 어딨어요? 미리듣고오라는데요
0
82
2
강의가완전 오래되서 다 틀리네 app.jsx도 tailwind css 다틀림 무책임함
0
70
1
개발자도구에 redux란이 없어요
0
91
1
npx tailwindcss init -p 에서 계속 에러나요
0
94
1
쇼핑몰기능중 찜하기 기능은 어떻게 구현하나요
0
141
2
강의하다 줌으로 설명가능한지좀 정확히 알려주세요. 이 선생님 정책이 어떻게 되는데요. 직접 연락할 메일이라도 알려주세요
0
44
1
도표 강의 자료 열람 불가능
0
110
1
tailwindcss를 vite에서 이용하는 방식이 바뀐것 같습니다.
0
1140
2
eslint 설정 후 오류가 납니다.
0
224
1
오버로드 오류
0
154
1
VSCode에서 save를 할 때, landingpage의 useEffect가 실행되는 문제에 대하여
0
171
1
dispatch(logoutUser()) 실행시 dispatch(authuser())도 함께 실행되는 문제
0
231
2
logout할 때, server로 요청을 보내서 authUser middleware를 통과하도록 하는 이유?
0
197
1
webkit-text-size-adjust 오류
0
317
1
does not provide an export named 'userReducer'
0
219
2
빌드 배포
0
140
1
삭제 예정 강의는 언제 삭제 되나요? 저것때문에 수강완료를 못하면 회사에서 비용을 청구한다고 합니다~
0
224
2





