问题
I am trying to use Draft.js in the Blog app I am creating. It all seems fine when saving data to the database and getting it back, just I cannot seem to get createWithContent to work.
When I write the following, the data does get saved to the database as I am simply creating an empty editor which then is updated by the user and sent to the database after convertToRaw.
const postDetails = useSelector((state) => state.postDetails);
const { loading, post, error } = postDetails;
const editorContent = EditorState.createEmpty();
const [editorState, setEditorState] = useState({ editorState: editorContent });
const handleEditorChange = (editorState) => { setEditorState({ editorState }) }
const submitHandler = (e) => {
e.preventDefault();
dispatch(
updatePost({
_id: id,
title,
image,
images,
paragraph: JSON.stringify(
convertToRaw(editorState.editorState.getCurrentContent())
),
})
);
};
<Editor
editorState={editorState.editorState}
onEditorStateChange={handleEditorChange}
/>
But when I use
EditorState.createWithContent(convertFromRaw(JSON.parse(post.paragraph)))
which is what I really want (the paragraph to be filled out with the post.paragrah coming from the database), I get the following error:
A cross-origin error was thrown. React doesn't have access to the actual error object in development.
I am taking care of cross-origin this way:
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
Also, when i console.log(post.paragraph) i do get my paragraph:
but what i noticed is that i also get 2 undefined before receiving my paragraph and this could be part of the issue.
To fix this i have tried both this:
const editorContent = post ?
EditorState.createWithContent(convertFromRaw(JSON.parse(post.paragraph))) :
EditorState.createEmpty();
const [editorState, setEditorState] = useState({ editorState: editorContent });
and this:
const editorContent = await post.paragraph;
if (post.paragraph) {
res.send({ editorContent: EditorState.createWithContent(convertFromRaw(JSON.parse(post.paragraph))) });
} else {
res.send({ editorContent: EditorState.createEmpty()});
}
return editorContent;
})
const [editorState, setEditorState] = useState({ editorState: content });
I have done lots of research on the web but I didn't manage to come up with anything successfull. Hope you guys can help. Thanks in advance
来源:https://stackoverflow.com/questions/64850515/draft-js-unable-to-get-data-from-the-database-cross-origin-error