When I send request like FormData via axios, body-parser doesn't read parameters. But when I send request like json, it reads. I use form-data because I sent imageFile so I have to use FormData.
Also I use express-validator, it always gives error because it can not read parameters. By the way, I don't try parse image with body-parser. I use multer. My problem is that body-parser can not read paramaters except image.
Html Part :
let formData = new FormData();
formData.append("email", "1@gmail.com");
formData.append("name", "1");
formData.append("password", "12345678901");
let imagefile = document.querySelector('#uploadImg');
formData.append("myFile", imagefile.files[0])
let url = "http://localhost:8080/;
axios({url: url,
data: formData,
method: "Post",
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': `multipart/form-data`,
}
}).then(x => {
console.log(x);
})
Node.js Part :
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const { check, validationResult } = require("express-validator");
app.use(cors());
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.text({ type: "text/html" }));
app.post(
"/sa",
[
check("email", "Email Hatalı").isEmail(),
check("name", "Name Hatalı").isLength({ min: 5 }),
check("password", "Password Hatalı").isLength({ min: 10 })
],
(req, res, next) => {
console.log(req.body);
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors.mapped());
return res.status(422).json({ errors: errors.array() });
}
res.send(200);
}
);
Express-Validator Error Output :
{ email:
{ value: undefined,
msg: 'Email Hatalı',
param: 'email',
location: 'body' },
name:
{ value: undefined,
msg: 'Name Hatalı',
param: 'name',
location: 'body' },
password:
{ value: undefined,
msg: 'Password Hatalı',
param: 'password',
location: 'body' } }
I have only one problem here. Body-parser don't parse request and validation read empty parameter.