How can I fix the code so I can upload image to mongodb and not getting post error?

DvdiidI

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 class="new_user">
    <div class="form-group">
        <label for="image" class="text-light">Profile Picture<br><br></label>
        <div id="image">
            Choose File
            <input type="file" id="image" name="image" accept="image/*" class="hide_file">
        </div>
    </div>
    <div class="form-group">
        <label for="name" class="text-light"><br><br>Name</label>
        <input type="hidden" name="id" value="">
        <input type="text" name="name" value="" placeholder="Mark Harris">
    </div>
    <div class="form-group">
        <label for="Email" class="text-light">Email</label>
        <input type="text" name="email" value="" placeholder="[email protected]">
    </div>
    <div class="form-group">
        <label for="gender" class="text-light">Gender</label>
        <div class="radio inline">
            <input type="radio" id="radio-1" name="gender" value="Male" >
            <label for="radio-1" class="radio-label">Male</label>
        </div>
        <div class="radio inline">
            <input type="radio" id="radio-2" name="gender" value="Female" >
            <label for="radio-2" class="radio-label">Female</label>
        </div>
    </div>
    <div class="form-group">
        <label for="favorite_movies" class="text-light">Favorite Movies</label>
        <textarea name="favorite_movies" placeholder="Avengers: Age of Ultron&#10Shrek&#10..."></textarea>
    </div>
    <div class="form-group">
        <button type="submit" class="btn text-dark update">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 = .......

traynor

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); 

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how can i fix this error in a bison code?

Why am I getting an attribute error? How can I fix it?

Mongodb ssl certificate error in python, how can i fix the error?

How i can upload an image with CreateView on my post?

How can i upload and post an image to linkedin using api?

im getting a logical error, how can i fix this?

How can I fix the code so Python will select the random number

How can I fix this error?

how can i fix this runtime error for a simple code written in c?

how can I fix this error in this code? index out of range

How can i fix the .NullPointerException error without code errors?

How can I fix a SqlException incorrect syntax error in my code?

How can I fix this error in my code for an assignment?

How can I fix sfml c++ code compilation error?

How can I fix this error in my python code?

How can I fix the error: ‘else’ without a previous ‘if’ in this code?

Unable to create a class on Parse server. Getting error code 1 - internal server error ... how can I fix this issue?

I'm getting an error in the Unity Editor saying that I have multiple plugins. How can I fix this?

How can I fix setState() so that it works?

I am getting blob errors in my console, how can i track them down, so I can fix them?

I keep getting this error and i can't seem to fix it

How can i fix transparency in image? PIL

How i can upload image to the article?

How can i upload image with ajax in codeigniter?

How can I upload an image with AJAX?

How can I upload the image file with axios?

How can i change html or javascript code, so when i click divs even it doesnt work .How can I fix it?

How can I fix this code for WPF Application?

How can I fix this code with unstoppable loop?