【问题标题】:Can't reach server, React 404 error 'Post'无法访问服务器,React 404 错误“发布”
【发布时间】:2022-01-11 23:27:44
【问题描述】:

我无法到达服务器端我检查了它应该工作的一切 错误是: “POST http://localhost:3000/404(未找到)”

这是我的代码

在这里的客户端,我在 jsx 文件和 actions/post.js 文件中调用 createPost:

import * as api from "../api/index";  
import * as types from "./types";

export const createPost = (post) => async (dispatch) =>{
    try {
        const {data} = await api.createPost(post);
        dispatch({
            type: types.CREATE_POST,
            payload: data,
        });

    } catch (error) {
        console.log(error);
    }
};

从这里它应该调用 api,

import axios from "axios";
const apiEndpoint = "/";

export const fetchPosts = async () => await axios.get(apiEndpoint);
export const createPost = async (post) => await axios.post(apiEndpoint, post);

然后从那里到服务器端,但首先在 createPost 处出错。

顺便说一句,在服务器中,

import express from "express";
import {getPosts, createPost} from "../contollers/posts.js";


const router = express.Router();

//localhost/posts
// GET POST DELETE UPDATE

router.get("/", getPosts);
router.post("/", createPost);

export default router;

在控制器中:

export const createPost = async(req,res) => {
const post = req.body;
const newPost = new Post(req.body);
try{
    await newPost.save();
    res.status(201).json(newPost);
}catch(error){
    res.status(409).json({
        message: error.message,
    });
}    

};

感谢帮助

【问题讨论】:

  • 您正在向 / 发出请求,这将是您的前端,而不是 API。您的 API 服务正在侦听哪个端口?
  • 在 3000 上收听
  • 那你是如何为你的 React 应用服务的呢?另外,您在哪里使用您的 Express 应用注册 router
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: javascript reactjs mern


【解决方案1】:

是的,我很愚蠢,将某些路由器和 dom 版本和 url 更正为 5000(这是服务器)解决了问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2017-07-02
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2015-02-18
    相关资源
    最近更新 更多