Javascript Can';你不能上快线吗?

Javascript Can';你不能上快线吗?,javascript,reactjs,express,Javascript,Reactjs,Express,我在一个mern项目上工作,我有一个小小的?错误: 当我尝试在特定路线上发帖时,express返回404,但找不到我想要的路线。 当我尝试发布到索引路径时,一切正常。以下是一个片段: in/controllers/imageController 图像控制器 exports.image_upload_post = (req,res) => { console.log('init file posting') } 输入/控制器/意外控制器 意外控制器(工作正常) 以下是路线: 路由/图

我在一个mern项目上工作,我有一个小小的?错误: 当我尝试在特定路线上发帖时,express返回404,但找不到我想要的路线。 当我尝试发布到索引路径时,一切正常。以下是一个片段:

in/controllers/imageController

图像控制器

exports.image_upload_post = (req,res) => {
   console.log('init file posting')
}
输入/控制器/意外控制器

意外控制器(工作正常)

以下是路线:

路由/图像上载路由:

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
/路由/索引路由:(工作路由)

最后,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)
我的问题是,为什么我要这样做:

const submitData = async (e) => {
   e.preventDefault()
   await axios.post('http://localhost:3001/upload', 'test')
}
在客户端React应用程序中,它返回404错误?如果我试图发布到http://localhost:3001/我得到控制器的日志“init file posting”?

你有

app.use('/upload', imageUploadRouter)
在imageUploadRouter文件中

router.post('/upload', image_upload_controller.image_upload_post)
这意味着您的完整路径将是

/upload/upload
而URL将是

http://localhost:3001/upload/upload
http://localhost:3001/upload
解决方案:将/upload替换为imageUploadRouter中的/upload

在这种情况下,URL将是

http://localhost:3001/upload/upload
http://localhost:3001/upload

问题在于,基本上您的路线不是
http://localhost:3001/upload
但应改为
http://localhost:3001/upload/upload
。您在“routes/imageUpload rout”和“index.js”中分别定义了一次。解决这个问题的一个简单方法是在索引文件中编写
app.use('/api',imageUploadRouter)
。然后您可以向
http://localhost:3001/api/upload

不客气!
http://localhost:3001/upload