0

// this is my exerciseController.ts

import { Request, Response, NextFunction } from 'express'
import { ExerciseModel } from '../models/Exercises'
import multer from 'multer'
import path from 'path'

type MulterFile = {
  fieldname: string
  originalname: string
  encoding: string
  mimetype: string
  destination: string
  filename: string
  path: string
  size: number
}

type MyRequestHandler = (
  req: Request,
  res: Response,
  next: NextFunction
) => void

const storage = multer.diskStorage({
  destination: function (req: Request, file: any, cb: any) {
    cb(null, path.join(process.cwd(), 'uploads'))
  },
  filename: function (req: Request, file: any, cb: any) {
    cb(null, new Date().toISOString() + file.originalname)
  }
})

const fileFilter = (req: Request, file: any, cb: any) => {
  if (file.mimetype.startsWith('image/')) {
    cb(null, true)
  } else {
    cb(new Error('Only image files are allowed!'), false)
  }
}

const upload: MyRequestHandler = multer({ storage, fileFilter }).array(
  'images',
  5
)

const allExercise = async (req: Request, res: Response): Promise<void> => {
  try {
    const response = await ExerciseModel.find({})
    res.json(response)
  } catch (err) {
    res.json(err)
  }
}

const createExercise = async (req: Request, res: Response): Promise<void> => {
  const exerciseData = req.body

  try {
    if (req.files && Array.isArray(req.files) && req.files.length > 0) {
      exerciseData.images = req.files.map((file: MulterFile) => file.path)
    } else {
      exerciseData.images = []
    }

    console.log('Exercise Data:', exerciseData)

    const exercise = new ExerciseModel(exerciseData)

    console.log('Saving exercise to the database...')
    const response = await exercise.save()
    console.log('Exercise saved successfully:', response)

    res.json(response)
  } catch (err: unknown) {
    console.error('Error occurred while saving exercise:', err)
    if (err instanceof Error) {
      res
        .status(500)
        .json({ error: 'Internal server error', message: err.message })
    } else {
      res.status(500).json({ error: 'Internal server error' })
    }
  }
}

export { allExercise, createExercise, upload }

// index.ts

import express, { Request, Response, NextFunction } from 'express'
import dotenv from 'dotenv'
import cors from 'cors'
import connectDB from './config/database'
import { userRouter } from './routes/users'
import { exerciseRouter } from './routes/exercises'

dotenv.config()

const port = process.env.PORT
const app = express()

app.use(express.json())
app.use(cors())

app.use('/auth', userRouter)
app.use('/exercise', exerciseRouter)
app.use('/uploads', express.static('uploads'))

app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  console.error('Unhandled Error:', err)
  res.status(500).json({ error: 'Internal server error' })
})

app.get('/', (req, res) => {
  res.send('Welcome to the server!')
})

connectDB()

app.listen(port, () => {
  console.log(`[server]: Server is running at http://localhost:${port}`)
})

// my router exercises.ts:

import express from 'express'
import { Request, Response, NextFunction } from 'express'
import multer from 'multer'
import {
  allExercise,
  createExercise,
  upload
} from '../controllers/exerciseController'

const router = express.Router()

router.route('/').get(allExercise)
router.route('/').post((req: Request, res: Response, next: NextFunction) => {
  upload(req, res, function (err: any) {
    if (err instanceof multer.MulterError) {
      return res.status(400).json({ error: 'File upload error' })
    } else if (err) {
      return res.status(500).json({ error: 'Internal server error' })
    }
    next()
  })
}, createExercise)

export { router as exerciseRouter }

my Model Exercises.ts:

import mongoose from 'mongoose'

const exerciseSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  images: {
    type: [
      {
        type: String
      }
    ],
    default: []
  },
  video: {
    type: String
  },
  tags: {
    type: [String],
    default: []
  },
  muscles: {
    type: [String],
    default: []
  },
  technique: {
    type: String
  },
  reps: {
    type: Number
  },
  sets: {
    type: Number
  },
  duration: {
    type: Number
  },
  userOwner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'users',
    required: true
  }
})

export const ExerciseModel = mongoose.model('Exercises', exerciseSchema)

when i run my terminal it's works fine : [nodemon] restarting due to changes... [nodemon] starting ts-node ./src/index.ts [server]: Server is running at http://localhost:8000 MongoDB Connected: ac-sthmh3d-shard-00-01.svrfvis.mongodb.net but when i send data with postman and try to upload an image, i got this : { "error": "Internal server error" } how i can avoid this error and send the data with the images upload

  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Jul 26 '23 at 01:39

0 Answers0