POST http://localhost:5173/posts 404(未找到)

POST http://localhost:5173/posts 404 (Not Found)

提问人:Simo Hamed 提问时间:7/10/2023 最后编辑:Brian Tompsett - 汤莱恩Simo Hamed 更新时间:8/19/2023 访问量:66

问:

我使用 react 和 vite 和 express 以及 MongoDB 构建了一个全栈博客,这是我第二次构建全栈应用程序,在第一个应用程序中,他们给了我同样的问题,我用邮递员测试了后端,一切正常,但是当我让我的 react 应用程序发送 API 请求时,他们给出的错误是我给出的路由找不到。

服务器 .js

const express = require('express');
const connectDB = require('./db/db');
const app = express();
const cors = require('cors');
const postRoutes = require('./routes/postRoutes')

app.use(cors({
    origin: "http://localhost:5173/posts"
}));


app.use(express.json())
app.use('/posts', postRoutes)


// start server
const port = 5173

const start =async ()=> {
    try {
        await connectDB(process.env.MONGO_URI)
        app.listen(port, ()=>{
        console.log(`Server running on port ${port}`)
    })
    } catch (error) {
        console.log(error)
    }
}
start()

post控制器

const Post = require('../models/Post')

const createPost = async (req, res)=>{
    const {title, content, author} = req.body
    try {
        const newPost = new Post({title, content, author})
        const savedPost = await newPost.save()
        res.status(201).json({message: 'Post creates successfully', Post: savedPost })
    } catch (error) {
        console.error(error)
        res.status(500).json({ message: 'An error occurred while creating the post' });
    }
}

const editPost = async (req, res)=>{
    const {title, content, author} = req.body
    const postId = req.params.id;

    try {
        const updatePost = await Post.findByIdAndUpdate(
            postId,
            {title, content, author},
            { new: true }
        )

        if(!updatePost){
            return res.status(404).json({ message:'No post found'})
        }

        res.json({ message: 'Post updated successfully', post: updatePost });
    } catch (error) {
        console.error(error)
        res.status(500).json({ message: 'An error occurred while updating the post' });
    }
}

const deletePost = async (req,res)=>{
    const postId= req.params.id

    try {
        const removePost = await Post.findByIdAndDelete(
            postId
        )
        if(!removePost){
            return  res.status(404).json({ message:"no such a post exist" })
        }
        res.json ({ message : "post deleted succesfully"})
    } catch (error) {
        console.error(error)
        res.status(500).json({ message: 'An error occurred while deleting the post' });
    }
}
module.exports = { createPost, editPost, deletePost }

后路由.js

const express = require('express')
const router = express.Router()

const { createPost, editPost, deletePost } = require('./postController')

// define the routes
router.post('/', createPost)
router.put('/:id', editPost)
router.delete('/:id', deletePost)

module.exports = router

我的反应

import { useRef, useState } from 'react';
import Header from '../components/Header'
import Footer from '../components/Footer'
import axios from 'axios'
import {CKEditor} from 'ckeditor4-react'
// import { Editor } from '@tinymce/tinymce-react';
// import ReactQuill from 'react-quill';
// import 'react-quill/dist/quill.snow.css';
import React from 'react'


const Add_Post = () => {
  const [title, setTitle] = useState("")
  const [content, setContent] = useState("")
  const [author, setAuthor] = useState("")
  const sendPost = async (e)=>{
    e.preventDefault()
    try {
      const response = await axios.post('http://localhost:5173/posts', {
        title : title,
        content : content,
        author : author
      })

      if(response.status === 201) {
        console.log('Post created successfully')
        setAuthor("")
        setContent("")
        setTitle("")
      }
    } catch (error) {
      console.error('Error creating post: ', error.message)
    }
  }
   const [value, setValue] = useState('');
  return (
    <div className='container'>
      <Header />
        <h1 style={{textAlign: "center"}} >Add Post</h1><br/>
        <form id="add-post-form" onSubmit={sendPost}>
            <label for="title">Title:</label><br/>
            <input type="text" id="title" name="title" value={title}
            onChange={(e)=>setTitle(e.target.value)}/><br/>
            <label for="content">Content:</label><br/>
            {/* <textarea id="content" name="content"></textarea><br/> */}
            <CKEditor
            onChange={(e)=>setContent(e.target.value)}
                initData="<p>Hello from CKEditor 4!</p>"
            value={content}/> <br />
            {/* <ReactQuill theme="snow" value={value} onChange={setValue} /> */}
            <label for="author">Author:</label><br/>
            <input type="text" id="author" name="author" value={author}
            onChange={(e)=>setAuthor(e.target.value)}/><br/>
            <button type="submit" className='add-post'>Add Post</button>
        </form>
        <Footer />
    </div>
  )
}

export default Add_Post
reactjs mongoDB express 错误处理

评论

0赞 Phil 7/10/2023
当前使用的 URL 用于前端服务。你想要http://localhost:5500/posts
0赞 Simo Hamed 7/11/2023
你是什么意思?
0赞 Phil 7/11/2023
好吧,在编辑问题之前,您已将 Express 应用程序绑定到端口 5500,但现在您已将其更改为 5173。不过,你的问题现在更令人困惑了......你的前端 React 应用在哪个端口上运行?这将是浏览器位置栏中显示的端口
0赞 Simo Hamed 7/11/2023
前端和后端都在端口 5000 上运行,我更改了端口以查看问题是否会得到解决,但没有任何一切正常,但是当前端发送 API 请求时,控制台给我错误 404 未找到
0赞 Phil 7/11/2023
这根本不可能,除非 Express 也通过 .不能将多个应用绑定到同一端口。express.static()

答: 暂无答案