我有一个nodejs服务器,它接受一个表单,并在用于检测裸露的API表示请求中的图像好之后将其插入到数据库中。如果我只是使用表单提交到端点,但现在我有一个函数可以防止默认情况下异步发送它不起作用。我使用formData发送整个表单数据,包括要插入数据库和验证码的图像文件,但我得到500 server error
,响应为Unexpected field
但是mutler期望相同的文件名是正如其他帖子建议发送可能是问题而Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
引用此行.then((res) => res.json())
发布到端点的代码
function submitForm(e) {
e.preventDefault();
var severity = document.getElementById('severity').value;
var address = document.getElementById('address-input').value;
var parish = document.getElementById('parish').value;
var lat = document.getElementById('lat').value;
var lon = document.getElementById('lon').value;
// var picture = document.getElementById('pic').value;
var captcha = document.querySelector('#g-recaptcha-response').value;
var input = document.querySelector('input[type=file]');
var data = new FormData(document.getElementById('ticketForm'))
data.append('pothole', input.files[0])
fetch("/ticket/add", {
method: "POST",
headers: {
"Accept": "application/json, text/plain, */*",
},
body: data
}).then((res) => res.json())
.then((data) => {
console.log(data)
//swal(data.msg);
if (data.msg === "failedCaptcha") {
swal("Failed captcha")
}
if (data.msg === 'success') {
swal({
title: 'Please remember the following code to delete ticket in the future ',
text: data.id,
type: 'warning',
//showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Ok'
}).then(function(result) {
// window.location.href = "/index.html";
})
}
if (data.msg === 'nude') {
swal({
title: 'It seems as if our system detected something inappropriate',
text: 'Email us with the information provided and we will analyze the image and upload on your behalf',
type: 'warning',
//showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Ok'
}).then(function(result) {
window.location.href = "/index.html";
})
}
})
}
服务器端点代码
app.post('/ticket/add', upload, function(req, res) {
//console.log(req.body)
// console.log(req.body['g-recaptcha-response'] + " this is captcha result");
if (!req.body.captcha) {
return res.json({ "success": false, "msg": "failedCaptcha" });
}
var secretKey = process.env.KEY;
var date = Date.now();
var id = uniqid();
var address = req.body.address;
address = address.split(',');
address = address[0];
var ticket = {
address: address,
comment: req.body.comment,
parish: req.body.parish,
type: req.body.type,
lat: req.body.lat,
long: req.body.lon,
severity: req.body.severity,
date: moment(date).format("MMM D,YYYY"),
time: moment(date).format('hh:mm A'),
picture: req.file,
deletionid: id,
ip: req.headers['x-forwarded-for'] || req.connection.remoteAddress
}
var verifyURL = `https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}
&response=${req.body.captcha }&remoteip=${req.connection.remoteAddress}`;
request(verifyURL, (err, response, body) => {
body = JSON.parse(body);
//If captcha is not successful
if (body.success !== undefined && !body.success) {
return res.json({ "success": false, "msg": "failedCaptcha" });
}
// If captcha is successful
sightengine.check(['nudity', 'wad']).set_file(path.join(req.file.path)).then(function(result) {
if (result.nudity.safe >= result.nudity.partial && result.nudity.safe >= result.nudity.raw) {
upload(req, res, function(err) {
if (err) {
console.log('Error Occured');
return;
}
db.collection('tickets').save(ticket)
return res.json({ "msg": "success", "id": id })
console.log("saved to db" + ticket);
});
} else {
return res.json({ "success": false, "msg": "nude" });
console.log('fail')
}
}).catch(function(err) {
// Error
});
})
});
更新
Multer Config
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'pothole/uploads/')
},
filename: function(req, file, cb) {
cb(null, file.originalname)
}
})
var upload = multer({ storage: storage }).single('pothole');
服务器输出
Error: Unexpected field
at makeError (/Users/islander/App/node_modules/multer/lib/make-error.js:12:13)
at wrappedFileFilter (/Users/islander/App/node_modules/multer/index.js:40:19)
at Busboy.<anonymous> (/Users/islander/App/node_modules/multer/lib/make-middleware.js:114:7)
at emitMany (events.js:127:13)
at Busboy.emit (events.js:201:7)
at Busboy.emit (/Users/islander/App/node_modules/busboy/lib/main.js:38:33)
at PartStream.<anonymous> (Users/islander/App/node_modules/busboy/lib/types/multipart.js:213:13)
at emitOne (events.js:96:13)
at PartStream.emit (events.js:188:7)
at HeaderParser.<anonymous> (/Users/islander/App/node_modules/dicer/lib/Dicer.js:51:16)