'Error using captcha and audio file in a html page
Im trying to use a captcha and send an audio file on same page. But I can't get the name of the file to send to the database. TypeError: Cannot destructure property 'filename' of 'req.file' as it is undefined.
I try to put on only one function to send the info but then the capctha doesn't work.
form.onsubmit = async e =>{
e.preventDefault()
form = e.target
var data2 = new FormData(form);
var request = new XMLHttpRequest();
data2.append('file',this.ablob);
request.open('post','/posts');
request.send(data2);
}
document.getElementById('form').addEventListener('submit', e => {
e.preventDefault();
const captcha = document.querySelector('#g-recaptcha-response').value;
return fetch('/posts', {
method: 'POST',
headers: {'Content-type': 'application/json'},
body: JSON.stringify({captcha}),
})
.then(res => res.json())
.then(data => {
console.log(data);
alert(data.msg);
if (data.success) return location.reload();
});
});
The back-end code:
routes.post("/posts", multer(multerConfig).single('file') , async(req, res) => {
if (!req.body.captcha)
return res.json({ success: false, msg: 'Please select captcha' });
// Secret key
const secretKey = '6Le1BJ4fAAAAADxI5gIDcnZcMEk5YpXNslAdos4g';
// Verify URL
const query = stringify({
secret: secretKey,
response: req.body.captcha,
remoteip: req.connection.remoteAddress
});
const verifyURL = `https://google.com/recaptcha/api/siteverify?${query}`;
// Make a request to verifyURL
const body = await fetch(verifyURL).then(res => res.json());
// If not successful
if (body.success !== undefined && !body.success)
return res.json({ success: false, msg: 'Failed captcha verification' });
// If successful
const {filename:name, size, key, location: url = '' } = req.file
const post = await Post.create({
name,
size,
key,
url,
emotion: req.body.emotion,
age: req.body.age,
gender: req.body.gender,
IP: req.ip,
description: req.body.others
})
return res.json({ success: true, msg: 'Captcha passed' });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
