Reputation: 45
I am working on a mern project and I have this tiny? error: When I try to post on a specific route, express returns 404 and can't find the route I wanted. Everything works fine when I try to post to the index route '/'. Here is a snippet:
in /controllers/imageController
ImageController
exports.image_upload_post = (req,res) => {
console.log('init file posting')
}
in /controllers/accidentController
AccidentController(works fine)
exports.accident_detail_post = (req,res) => {
console.log('init form data posting')
}
Here are the routes:
routes/imageUpload route:
const express = require('express')
const router = express.Router()
const image_upload_controller = require('../controllers/ImageUploadController')
router.post('/upload', image_upload_controller.image_upload_post)
module.exports = router
/routes/index route: (the working one)
const express = require('express')
const router = express.Router()
const accident_detail_controller = require('../controllers/AccidentController')
router.post('/', accident_detail_controller.accident_detail_post)
module.exports = router
And finally, server.js:
const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
const app = express()
const indexRouter = require('./routes/index')
const imageUploadRouter = require('./routes/imageUpload')
app.use(cors())
app.use(express.json())
app.use('/', indexRouter)
app.use('/upload', imageUploadRouter)
And my question is, why when I try to do something like this:
const submitData = async (e) => {
e.preventDefault()
await axios.post('http://localhost:3001/upload', 'test')
}
in the client React app, it returns 404 error? If I try to post to http://localhost:3001/ I get the controller's log 'init file posting'?
Upvotes: 1
Views: 62
Reputation: 2545
You have
app.use('/upload', imageUploadRouter)
and in the imageUploadRouter file, you have
router.post('/upload', image_upload_controller.image_upload_post)
that means your full path will be
/upload/upload
and URL will be
http://localhost:3001/upload/upload
Solution: replace the /upload by / in the imageUploadRouter
router.post('/', image_upload_controller.image_upload_post)
In this case, the URL will be
http://localhost:3001/upload
Upvotes: 1
Reputation: 355
The problem is that essentially your route is not http://localhost:3001/upload
but instead http://localhost:3001/upload/upload
. You are defining it once in 'routes/imageUpload rout' and again in 'index.js'. An easy fix for this would be to write app.use('/api', imageUploadRouter)
in the index file. Then you can make your requests to http://localhost:3001/api/upload
Upvotes: 0