首页 > 解决方案 > POST 请求未通过 (MERN)

问题描述

我第一次使用 MERN 堆栈构建应用程序。

为了记录 HTTP 请求,我使用“morgan”。

我设法将数据发送到似乎工作正常的 mongodb。问题是我的帖子请求没有通过。它说“待定”4分钟,然后失败。

这是我认为我的代码的相关部分:

“服务器.js”:

const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");

const app = express();

const PORT = process.env.PORT || 8080;

const routes = require("./routes/api");

const MONGODB_URI =
    "...";

mongoose.connect(MONGODB_URI || "mongodb://localhost/app", {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

mongoose.connection.on("connected", () => {
    console.log("Mongoose is connected.");
});

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(cors());

app.use(morgan("tiny"));

app.use("/api", routes);

app.listen(PORT, console.log(`Server is starting at ${PORT}`));

然后我把我的路线放到另一个文件“api.js”中:

const express = require("express");

const router = express.Router();

const Lane = require("../models/lanes");

router.get("/", (req, res) => {
    Lane.find({})
        .then(data => {
            res.json(data);
            console.log("Get request successful!");
        })
        .catch(error => {
            console.log("Error: ", error);
        });
});

router.post("/save", (req, res) => {
    const data = req.body;
    const newLane = new Lane();
    newLane.collection.insertMany(data, err => {
        if (err) {
            console.log(err);
        } else {
            console.log("Multiple docs inserted");
        }
    });
});

module.exports = router;

我正在使用 axios 发送请求。在我的应用程序中提交表单后会发生这种情况。

减速机功能:

const reducer = (state, action) => {
    switch (action.type) {
        case "add":
            axios({
                url: "http://localhost:8080/api/save",
                method: "POST",
                data: [...state, { id: uuid(), title: action.title, tasks: [] }]
            })
                .then(() => {
                    console.log("Data has been sent to the server");
                })
                .catch(() => {
                    console.log("Internal server error");
                });
            return [...state, { id: uuid(), title: action.title, tasks: [] }];

我的上下文提供程序组件正在使用减速器,如下所示:

export function LanesProvider(props) {
    const [lanes, dispatch] = useReducer(reducer, defaultLanes);

    return (
        <LanesContext.Provider value={lanes}>
            <DispatchContext.Provider value={dispatch}>
                {props.children}
            </DispatchContext.Provider>
        </LanesContext.Provider>
    );
}

当在另一个组件中提交表单时,我的 reducer 中的“add”方法被调用。

如果我可以在我的问题中添加任何有帮助的内容,请告诉我。

先感谢您!

标签: node.jsreactjsexpressxmlhttprequestaxios

解决方案


您没有向客户端发送任何响应。尝试修改 post 方法,如

router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane();
newLane.collection.insertMany(data, err => {
    if (err) {
        console.log(err);
        res.send(err)
    } else {
        console.log("Multiple docs inserted");
        res.send("Multiple docs inserted")
    }
});
});

推荐阅读