我目前面临的问题是我发出了一个包含图像的 axios Post multipart/form-data 请求。这来自 TinyMCE 编辑器组件的 file_picker_callback。
<Editor
onInit={(evt, editor) => (editorRef.current = editor)}
initialValue={service?.description || ""}
init={{
apiKey: tinyApiKey,
height: 1000,
menubar: false,
plugins: ["image", "link"],
toolbar:
"h1 h2 h3 | image link | formatselect | " +
"bold | alignleft aligncenter " +
"alignright alignjustify | bullist numlist outdent indent | " +
"removeformat | help",
content_style:
"body { font-family:Helvetica,Arial,sans-serif; font-size:14px }",
images_upload_url:
`${process.env.REACT_APP_BACKEND_URL}/api/upload`,
file_picker_callback: (callback, value, meta) => {
const input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("name", "image");
input.setAttribute("accept", "image/*");
input.onchange = () => {
const file = input.files[0];
const formData = new FormData();
formData.append("file", file);
axios
.post(`${process.env.REACT_APP_BACKEND_URL}/api/upload`,
formData)
.then((response) => {
const editor = window.tinymce.activeEditor;
const img = `<figure className="img-container"><img src="${response.data.location}" alt="descriptive"/></figure>`;
editor.insertContent(img);
callback(response.data.location);
})
.catch((error) => {
console.log(error);
});
};
input.click();
},
}}
/>
后端路由包含2个中间件,第一个是authMiddleware,第二个是multer,我的请求无法通过authMiddleware。
路由器:
const protect = require("../middleware/authMiddleware");
const { upload } = require("../utils/fileUpload");
router.post("/", protect, upload.single("file"), uploadImage);
authMiddleware.js :
const jwt = require("jsonwebtoken");
const User = require("../models/userModel");
const asyncHandler = require("express-async-handler");
const protect = asyncHandler(async (req, res, next) => {
try {
const token = req.cookies.token;
// Valiadate
if (!token) {
res.status(401);
throw new Error("Not authorized, please log in");
}
// Verify
const verified = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(verified.id).select("-password");
if (!user) {
res.status(404);
throw new Error("User not found");
}
req.user = user;
next();
} catch (error) {
res.status(401);
throw new Error("Not authorized, please log in");
}
});
module.exports = protect;
上传控制器.js:
const asyncHandler = require("express-async-handler");
const { fileSizeFormatter } = require("../utils/fileUpload");
const uploadImage = asyncHandler(async (req, res) => {
fileData = {
fileName: req.file.originalname,
filePath: req.file.path,
fileType: req.file.mimetype,
fileSize: fileSizeFormatter(req.file.size, 2),
};
res.status(201).json({
location: `${req.protocol}://${req.hostname}:5000/${req.file.path}`,
});
});
module.exports = {
uploadImage,
};
我检查了控制台,错误是 Not Authorized,please log in which is from authMiddleware,我还检查了请求没有发送任何 cookie。我也有:
axios.defaults.withCredentials = true;
我检查了控制台,错误是 Not Authorized,please log in which is from authMiddleware,我还检查了请求没有发送任何 cookie。我也有:
axios.defaults.withCredentials = true;