提问人:Simo Hamed 提问时间:7/10/2023 最后编辑:Brian Tompsett - 汤莱恩Simo Hamed 更新时间:8/19/2023 访问量:66
POST http://localhost:5173/posts 404(未找到)
POST http://localhost:5173/posts 404 (Not Found)
问:
我使用 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
答: 暂无答案
评论
http://localhost:5500/posts
express.static()