node.js - 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”方法被调用。
如果我可以在我的问题中添加任何有帮助的内容,请告诉我。
先感谢您!
解决方案
您没有向客户端发送任何响应。尝试修改 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")
}
});
});
推荐阅读
- advanced-custom-fields - 如何在自定义分类页面的存档页面上显示自定义字段
- wordpress - Wordpress WooCommerce BeRocket 滤色器未显示
- reactjs - React 将一个函数传递给另一个组件
- flutter - Cmake 编译失败找不到 python.h (Flutter, dart:ffi)
- c# - 在原始上下文中等待长时间运行的任务
- laravel - vuejs循环遍历二维数组
- php - 如果在产品级别管理库存级别,自定义添加到购物车按钮不起作用
- questdb - Web控制台的Questdb身份验证?
- grpc - gRPC C++ 服务器实现,有哪些方法可以取消 RPC 的上下文?
- javascript - 当 Array 中的事物具有共同因素时,有什么好方法可以从新 Array 中获取新 Array 吗?(react.js)