Я пытаюсь загрузить изображение пользователя через панель администратора. (сервер: express) Затем, когда я нажимаю кнопку «Создать», консоль выдала мне следующие ошибки: .
маршруты / содержимое. js
const express = require("express");
const authorize = require("../middleware/authorize");
const router = express.Router();
const ContentController = require("../controllers/content");
const Content = require("../middleware/contents");
const thumbnails = require("../middleware/thumbnails");
const posters = require("../middleware/posters");
const trailers = require("../middleware/trailers");
router.post("/content/upload/artistThumbnail", authorize, thumbnails, ContentController.addArtist);
контроллеры / контент. js
exports.addArtist = async (req, res, next) => {
try {
let genre_id = req.body.genre_id;
let Fname = req.body.Fname;
let Lname = req.body.Lname;
let thumbnailURL = "thumbnails/" + req.file.filename;
let dateType = new Date().toJSON().slice(0, 10).replace(/-/g, '-');
const query = "insert into artist (name,thumbnailURL, genre_id, createdAt) values ('" + Fname + " " + Lname + "','" + thumbnailURL + "','" + genre_id + "', '" + dateType + "')";
database.executeQuery(res, "Added artist success.", query);
} catch (e) {
console.log('err:-========--------', e)
const response = {
'status_code': 500,
'error': "Internal Server Error"
};
res.status(500).json(response);
}
};
middleware / authorize. js
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
const bearerHeader = req.headers['authorization'];
if (typeof bearerHeader !== 'undefined') {
const token = bearerHeader.split(' ')[1];
jwt.verify(token, '8z6xw%C&?m<Md', (err, auth) => {
if (err) {
console.log("Token Authentication Failed");
res.status(401).json({
status_code: 401,
error: "Authentication Failed"
});
} else {
console.log("Token Verified");
next();
}
});
} else {
console.log("Header Not Found");
res.status(401).json({
status_code: 401,
error: "Authentication Failed"
});
}
}
middleware / thumbnails. js
const multer = require("multer");
const MIME_TYPE_MAP = {
"image/png": "png",
"image/jpeg": "jpg",
"image/jpg": "jpg"
};
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const isValid = MIME_TYPE_MAP[file.mimetype];
let error = new Error("Invalid mime type");
if (isValid) {
error = null;
}
cb(error, "public/thumbnails");
},
filename: (req, file, cb) => {
const name = file.originalname
.toLowerCase()
.split(" ")
.join("-");
cb(null, Date.now() + "-" + name);
}
});
module.exports = multer({ storage: storage }).single("thumbnail");
src / artist_create. html
<form action="" method="post" id="register_form" enctype="multipart/form-data">
<div class="form-group">
<!-- upload movie start -->
<label class="col-md-1 control-label">Photo:</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="thumbnails" name="thumbnails" />
</span>
<a href="#" class="btn btn-default fileupload-exists"
data-dismiss="fileupload">Remove</a>
</div>
</div>
</div>
<!-- upload movie start -->
</div>
<div class="form-group">
<input type="button" class="btn btn-success" onclick="createArtist()"
value="Create">
<a href="./artist.html" class="btn btn-black">Go back</a>
</div>
</form>
... ... ...
<script>
async function createArtist() {
var formData = new FormData();
formData.append('Fname', $('#Fname').val())
formData.append('Lname', $('#Lname').val());
formData.append('genre_id', $('#genre_id').val());
formData.append('thumbnails', $('#thumbnails').prop('files')[0]);
let user = JSON.parse(window.localStorage.getItem('USER'));
let response = await fetch('http://192.168.16.29:8000/api/content/upload/artistThumbnail', {
method: 'POST',
headers: {
// 'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'bearer ' + user.token.value
},
body: formData
});
let result = await response.json();
console.log('res======', result);
if (result.status_code === 200) {
window.location = "artist.html";
} else {
alert('Something gone wrong please try again');
console.log(result);
}
}
</script>
Как решить Эта проблема? Пожалуйста, помогите мне.