There is no such problem local. However, in the React app distributed to Heroku, there are no cors errors when writing text in the react quill and sign up, or working with various servers such as login. However, if I upload an image to the react quill, a cors error occurs. Can I know why occurs and how to solve it? I can't proceed with anything else because of this for a week.(Additionally, sometimes it works well without errors when uploading images. That's why I don't understand it all the more.)
React used Apollo, and the server used graphql.
This is React code.
let imgUrl = "";
const EditorComponent = ({ title, classification }) => {
const QuillRef = useRef();
const [contents, setContents] = useState("");
const formData = new FormData();
// I get url from the server.
const onCompleted = (data) => {
const {
singleUpload: { url },
} = data;
imgUrl = url;
};
const [singleUpload] = useMutation(UPLOAD_FILE, {
onCompleted,
});
// 이미지를 업로드 하기 위한 함수
const imageHandler = () => {
// 파일을 업로드 하기 위한 input 태그 생성
const input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("accept", "image/*");
input.click();
// 파일이 input 태그에 담기면 실행 될 함수
input.onchange = async () => {
let file = input.files;
if (file !== null) {
formData.append("image", file[0]);
console.log(formData.get("image"));
// Upload an image on graphql.
await singleUpload({
variables: {
file: formData.get("image"),
},
});
try {
let res = "";
// 커서의 위치를 알고 해당 위치에 이미지 태그를 넣어주는 코드
// 해당 DOM의 데이터가 필요하기에 useRef를 사용한다.
const range = QuillRef.current?.getEditor().getSelection()?.index;
if (range !== null && range !== undefined) {
let quill = QuillRef.current?.getEditor();
quill?.setSelection(range, 1);
// 이미지 사이즈는 quill.snow.css에서 조절.
quill?.clipboard.dangerouslyPasteHTML(
range,
`<img src=${imgUrl} alt="이미지 태그가 삽입됩니다." />`
);
}
formData.delete("image");
return { ...res, success: true };
} catch (error) {
const err = error;
return { ...err.response, success: false };
}
}
};
};
This is resolvers in Graphql
import path from "path";
import fs from "fs";
// import { GraphQLUpload } from "graphql-upload";
function generateRandomString(length) {
var result = "";
var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
export default {
// Upload: GraphQLUpload,
Mutation: {
singleUpload: async (obj, { file }) => {
const { filename, createReadStream } = await file;
const { ext } = path.parse(filename);
const randomName = generateRandomString(12) + ext;
const stream = createReadStream();
const pathName = path.join(
__dirname,
process.env.NODE_ENV !== "production"
? `../../../public/imagesLocal/${randomName}`
: `../../../public/images/${randomName}`
);
await stream.pipe(fs.createWriteStream(pathName));
return {
url:
process.env.NODE_ENV !== "production"
? `http://localhost:4000/imagesLocal/${randomName}`
: `https://unit-backend.herokuapp.com/images/${randomName}`,
};
},
},
};
This is typeDefs in Graphql
import { gql } from "apollo-server";
export default gql`
scalar Upload
type File {
url: String!
}
type Mutation {
singleUpload(file: Upload!): File!
}
`;
It's an error image. enter image description here