I am making a text editor for my blog (Using React) and using CKEditor for it. I am using an express server on a windows machine to handle the image upload request. When I browse the uploads directory on the windows machine, the file is present but on the CKEditor page I get the following error:
This is the CKEditor component code (using react):
JavaScript
x
18
18
1
<CKEditor
2
editor={ClassicEditor}
3
data='<p>Hello World</p>'
4
onChange={(event,editor) => {
5
setHtml(editor.getData());
6
console.log(html)
7
}}
8
config={
9
{
10
ckfinder: {
11
uploadUrl:'http://localhost:8000/upload'
12
}
13
}
14
}
15
/>
16
17
18
This is the server code (Using express):
JavaScript
1
25
25
1
const express = require('express');
2
const PORT = 8000;
3
const app = express();
4
const bodyparser = require('body-parser'); //Body parsing middle ware
5
const morgan = require('morgan'); //HTTP request logger middle ware
6
const multipart = require('connect-multiparty');
7
const MultipartMiddleWare = multipart({uploadDir:'./uploads'});
8
const cors = require('cors'); // Middle ware to handle cors
9
10
app.use(cors())
11
app.use(bodyparser.urlencoded({extended: true}));
12
app.use(bodyparser.json());
13
app.get('/', (req, res) => {
14
res.status(200).json({
15
message: "Test MSG"
16
})
17
})
18
19
app.post('/upload',MultipartMiddleWare,(req,res) => {
20
res.send("Success");
21
console.log(req.files.upload)
22
})
23
24
app.listen(PORT, console.log(`server has successfully startet at PORT: ${PORT}`))
25
JavaScript
1
1
1
Advertisement
Answer
The correct response for uploaded image is
JavaScript
1
5
1
{
2
uploaded: true,
3
url: 'path to uploaded image'
4
}
5
so in your app.post use the following code:
JavaScript
1
11
11
1
app.post('/upload',MultipartMiddleWare,(req,res) => {
2
3
let tempFile = req.files.upload;
4
let path = tempFile.path;
5
6
res.status(200).json({
7
uploaded: true,
8
url: `http://localhost:8000/${path}`
9
})
10
})
11