I am using Node.js to write to a Mongo Database. When my front end form is submitted it comes back with an error about one of the fields being empty when it is not. The specific field it is hanging up on is the author field, but it could be that it's just the first one and all of them will produce an error. Can anyone advise on what I am doing wrong?
Routes.js
//Article routes //list all articles app.get("/articles", function (req, res) {
Article.findAll(function (error, results) {
if (error) {
res.json(error, 'findall not working');
} else if (!results) {
res.send(404);
} else {
var i = 0, stop = results.length;
for (i; i < stop; i++) {
results[i].image = undefined;
}
res.json(results);
}
}); });
// get the JSON representation of just one article app.get("/article/:id", function (req, res) {
Article.findById(req.params.id, function (error, result) {
if (error) {
res.json(error, 400);
} else if (!result) {
res.send(404);
} else {
result.image = undefined;
res.json(result);
}
}); });
// get the image of a particular article
app.get("/article/:id/image", function (req, res) {
Article.findById(req.params.id, function (error, result) {
if (error) {
res.json(error, 400);
} else if (!result || !result.imageType || !result.image || !result.image.buffer || !result.image.buffer.length) {
res.send(404);
} else {
res.contentType(result.imageType);
res.end(result.image.buffer, "binary");
}
});
});
// save/update a new article
app.post("/article", function (req, res, next) {
var input = req.body;
if (!input.author) {
res.status('author must be specified').json('author');
return;
}
if (!input.content) {
res.status('content must be specified').json(400);
return;
}
Article.save(input, req.files.image, function (err, objects) {
if (err) {
res.json(error, 400);
} else if (objects === 1) { //update
input.image = undefined;
res.json(input, 200);
} else { //insert
input.image = undefined;
res.json(input, 201);
}
});
});
Index.html
<h2>Upload an Image</h2>
New article form:
<form method="post" enctype="multipart/form-data" action="/article">
<label for="author">Author: </label>
<input type="text" name="author"/>
<br/>
<label for="content">Content: </label>
<br/>
<textarea rows="5" cols="100" name="content"></textarea>
<br/>
<label for="image">Image(optional): </label>
<input type="file" name="image"/>
<br/>
<input type="submit"/>
</form>