I have some user info that I want to save in mongodb database. I checked API post with postman by filling in some form-data fields in body. Simple data such as name or email, simple Strings work perfectly, but when I changed code(in controller.js file) so I can also get image file, it throws this generic error: "Cannot POST /api/users". The code seems fine to me but something's missing and can't figure it out.
server.js file:
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const bodyparser = require("body-parser");
const path = require('path');
const fileUpload = require('express-fileupload');
const connectDB = require('./server/database/connection');
const bodyParser = require('body-parser');
const app = express();
app.use(fileUpload());
dotenv.config({path : 'config.env'})
const PORT = process.env.PORT || 8080
//log requests
app.use(morgan('tiny'));
//mongodb connection
connectDB();
//parse request to body-parser
app.use(bodyparser.urlencoded({extended : false}))
app.use(bodyparser.json())
//set view engine
app.set("view engine", "ejs")
//app.set("views", path.resolve(__dirname, "views/ejs"))
//load assets
app.use('/css', express.static(path.resolve(__dirname, "assets/css")))
app.use('/img', express.static(path.resolve(__dirname, "assets/img")))
app.use('/js', express.static(path.resolve(__dirname, "assets/js")))
//load routers
app.use('/', require('./server/routes/router'))
app.listen(PORT, ()=>{console.log(`Server is running on http://localhost:${PORT}`)});
router.js file:
const express = require('express');
const route = express.Router()
const services = require('../services/render');
const controller = require('../controller/controller');
route.get('/', services.homeRoutes);
route.get('/add-user', services.add_user);
route.get('/update-user', services.update_user);
//API
route.post('/api/users', controller.create);
route.get('/api/users', controller.find);
route.put('/api/users/:id', controller.update);
route.delete('/api/users/:id', controller.delete);
module.exports = route
model.js file:
const mongoose = require('mongoose');
var schema = new mongoose.Schema({
profile_picture: {
data: Buffer,
contentType: String
},
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
gender: String,
favorite_movies: {
type: String,
text: true
}
})
const Userdb = mongoose.model('userdb', schema);
module.exports = Userdb;
controller.js file:
var multer = require('multer');
var fs = require('fs');
var path = require('path');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname '-' Date.now())
}
});
var upload = multer({ storage: storage });
var Userdb = require('../model/model');
//create and save new user
exports.create = upload.single('image'), (req, res, next)=>{
//validate request
if(!req.body){
res.status(400).send({ message : "Content cannot be empty!"});
return;
}
//new user
const user = new Userdb({
profile_picture : {
data: fs.readFileSync(path.join(__dirname '/uploads/' req.file.filename)),
contentType: 'image/png'
},
name : req.body.name,
email : req.body.email,
gender : req.body.gender,
favorite_movies : req.body.favorite_movies
})
//save user in the database
user
.save(user)
.then(data=>{
//res.send(data)
res.redirect('/add-user');
})
.catch(err=>{
res.status(500).send({
message : err.message || "Some error occurred while creating a create operation"
});
});
}
_form.ejs file:
<!-- form handling -->
<form action="/api/users" method="POST" id="add_user">
<div >
<div >
<label for="image" >Profile Picture<br><br></label>
<div id="image">
Choose File
<input type="file" id="image" name="image" accept="image/*" >
</div>
</div>
<div >
<label for="name" ><br><br>Name</label>
<input type="hidden" name="id" value="">
<input type="text" name="name" value="" placeholder="Mark Harris">
</div>
<div >
<label for="Email" >Email</label>
<input type="text" name="email" value="" placeholder="[email protected]">
</div>
<div >
<label for="gender" >Gender</label>
<div >
<input type="radio" id="radio-1" name="gender" value="Male" >
<label for="radio-1" >Male</label>
</div>
<div >
<input type="radio" id="radio-2" name="gender" value="Female" >
<label for="radio-2" >Female</label>
</div>
</div>
<div >
<label for="favorite_movies" >Favorite Movies</label>
<textarea name="favorite_movies" placeholder="Avengers: Age of Ultron
Shrek
..."></textarea>
</div>
<div >
<button type="submit" >Save</button>
</div>
</div>
</form>
I believe the problem is somewhere in this controller.js file where I create and save a new user, the part exports.create = .......
CodePudding user response:
the problem is that the route handler is not implemented correctly: it returns upload middelware, and the response is not handled
you need to split them, export upload and create, and then call them in the POST handler:
controller.js file:
exports.upload = upload.single('image');
//create and save new user
exports.create = (req, res, next)=>{
router.js file:
//API
route.post('/api/users', controller.upload, controller.create);