我第一次使用MERN堆栈构建应用程序。
为了记录HTTP请求,我使用“ morgan”。
我设法将数据发送到mongodb,看来工作正常。问题是我的发帖请求没有通过。它说“待定” 4分钟,然后失败。
这就是我认为与代码相关的部分:
“ server.js”:
public function index(Request $request, Features $features)
{
if ($features->isFeature1Enabled()) {
//
}
}
然后,我将路线放入另一个文件“ api.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}`));
我正在使用axios发送请求。在我的申请表中提交表单后,就会发生这种情况。
减速器功能
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;
我的上下文提供程序组件正在使用reducer,如下所示:
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: [] }];
在另一个组件中提交表单时,将调用我的reducer中的“ add”方法。
请让我知道我是否可以在问题中添加任何有帮助的内容。
提前谢谢!
答案 0 :(得分:2)
您没有将任何响应发送回客户端。尝试修改
之类的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")
}
});
});