Error in mongodb " Route.post() requires a callback function but got a [object Undefined]"

huangapple go评论77阅读模式
英文:

Error in mongodb " Route.post() requires a callback function but got a [object Undefined]"

问题

这是我的主文件 index.js

type here
const express = require("express");
const app = express();

require("dotenv").config();
const port = process.env.port || 4000;

app.use(express.json());

const createBlog = require("./routes/blogRoutes");

app.use("/santi/api/v1", createBlog);

app.listen(port, () => {
    console.log("App run in 3000 port");
})

const dbConnect = require("./config/database");
dbConnect();

app.get("/", (req, res) => {
    res.send("<h1>this is homepage</h1>");
})

这是我的路由文件

const express = require("express");
const router = express.Router();

const { createBlog } = require("../controlers/createBlog");

router.post("/createBlog", createBlog);

module.exports = router;

这是我的控制器文件

const createPost = require("../models/post");

exports.post = async (req, res) => {
    try {
        const { title, description } = req.body;
        const response = await createPost.create({ title, description });

        res.status(200).json({
            status: true,
            message: "插入成功",
            data: response
        })
    }
    catch (error) {
        console.error(err);
        res.status(500).json({
            status: false,
            message: error.message,
            data: "服务器问题"
        })
    }
}

这是我的模型文件

const mongoose = require("mongoose");

const blogPostSchema = new mongoose.Schema(
    {
        title: {
            type: String,
            required: true,
            maxlength: 50
        },
        description: {
            type: String,
            required: true,
            maxlength: 50
        }
    }
)

module.exports = mongoose.model("blogPost", blogPostSchema);

我安装了 nodemon 和 mongoose,但在运行 "npm run dev" 命令后仍然在终端中显示以下错误:

blog_backend@1.0.0 dev
nodemon index.js

[nodemon] 2.0.22
[nodemon] 若要随时重新启动,请输入 rs
[nodemon] 正在监视路径:.....
[nodemon] 正在监视扩展名:js, mjs, json
[nodemon] 启动 node index.js
C:\Users\SWETTA\OneDrive\Desktop\blog_backend\node_modules\express\lib\router\route.js:211
throw new Error(msg);
^

错误:Route.post() 需要回调函数,但得到了 [object Undefined]
在 Route.<计算值> [as post] (C:\Users\SWETTA\OneDrive\Desktop\blog_backend\node_modules\express\lib\router\route.js:211:15)
在 proto.<计算值> [as post] (C:\Users\SWETTA\OneDrive\Desktop\blog_backend\node_modules\express\lib\router\index.js:521:19)
在 Object.<匿名> (C:\Users\SWETTA\OneDrive\Desktop\blog_backend\routes\blogRoutes.js:6:8)
在 Module._compile (node:internal/modules/cjs/loader:1254:14)
在 Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
在 Module.load (node:internal/modules/cjs/loader:1117:32)
在 Module._load (node:internal/modules/cjs/loader:958:12)
在 Module.require (node:internal/modules/cjs/loader:1141:19)
在 require (node:internal/modules/cjs/helpers:110:18)
在 Object.<匿名> (C:\Users\SWETTA\OneDrive\Desktop\blog_backend\index.js:9:20)

解决方法是什么?

英文:

This is my main file index.js

type here
const express = require(&quot;express&quot;);
const app = express();

require(&quot;dotenv&quot;).config();
const port = process.env.port || 4000;

app.use(express.json());

const createBlog = require(&quot;./routes/blogRoutes&quot;);

app.use(&quot;/santi/api/v1&quot;,createBlog);

app.listen(port, () =&gt; {
    console.log(&quot;App run in 3000 port&quot;);
})

const dbConnect = require(&quot;./config/database&quot;);
dbConnect();

app.get(&quot;/&quot;, (req,res) =&gt; {
    res.send(`&lt;h1&gt;this is homepage&lt;/h1&gt;`);
})

this is my routes

const express = require(&quot;express&quot;);
const router = express.Router();

const {createBlog} = require(&quot;../controlers/createBlog&quot;);

router.post(&quot;/createBlog&quot;,createBlog);

module.exports = router;

this is my controller file

const createPost = require(&quot;../models/post&quot;);

exports.post = async (req,res) =&gt; {
    try {
        const {title,description} = req.body;
        const response = await createPost.create({title,description});

        res.status(200).json({
            status:true,
            message:&quot;Insert seccessfully&quot;,
            data:response
        })
    }
    catch(error) {
        console.error(err);
        res.status(500).json({
            status:false,
            message:error.message,
            data:&quot;Server issue&quot;
        })
    }
}

this is my model file

const mongoose = require(&quot;mongoose&quot;);

const blogPostSchema = new mongoose.Schema(
    {
        title:{
            type:String,
            required:true,
            maxlength:50
        },
        description:{
            type:String,
            required:true,
            maxlength:50
        }
    }
)

module.exports = mongoose.model(&quot;blogPost&quot;,blogPostSchema);

I install nodemon and mongoose but still follwing error show in terminal after write "npm run dev" command

> blog_backend@1.0.0 dev
> nodemon index.js

[nodemon] 2.0.22
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,json
[nodemon] starting node index.js
C:\Users\SWETTA\OneDrive\Desktop\blog_backend\node_modules\express\lib\router\route.js:211
throw new Error(msg);
^

Error: Route.post() requires a callback function but got a [object Undefined]
at Route.<computed> [as post] (C:\Users\SWETTA\OneDrive\Desktop\blog_backend\node_modules\express\lib\router\route.js:211:15)
at proto.<computed> [as post] (C:\Users\SWETTA\OneDrive\Desktop\blog_backend\node_modules\express\lib\router\index.js:521:19)
at Object.<anonymous> (C:\Users\SWETTA\OneDrive\Desktop\blog_backend\routes\blogRoutes.js:6:8)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Module.require (node:internal/modules/cjs/loader:1141:19)
at require (node:internal/modules/cjs/helpers:110:18)
at Object.<anonymous> (C:\Users\SWETTA\OneDrive\Desktop\blog_backend\index.js:9:20)

what is the solution ?

答案1

得分: 0

我在你的路由器代码中看到一个小错误。你在控制器中将函数导出为 post,并在路由器中以 createBlog 导入。但你的控制器没有导出任何名为 createBlog 的东西,因此问题就出在这里。

只需将路由器代码更改为这样:

const express = require("express");
const router = express.Router();

const { post } = require("../controlers/createBlog");

router.post("/createBlog", post);

module.exports = router;
英文:

I see a small error in your router code.
You are exporting the function as post in your controller and importing it in router as createBlog. And your controller does not export anything with the name createBlog and hence the issue is.

Just change the router code to this:

const express = require(&quot;express&quot;);
const router = express.Router();

const {post} = require(&quot;../controlers/createBlog&quot;);

router.post(&quot;/createBlog&quot;,post);

module.exports = router;

答案2

得分: 0

The issue is in your controller file, you are exporting the function under the name "post" and importing it in your routes file as "createBlog." To correct your code, you should update your controller and rename the function as "createBlog":

const createPost = require("../models/post");

exports.createBlog = async (req, res) => {
    try {
        const { title, description } = req.body;
        const response = await createPost.create({ title, description });

        res.status(200).json({
            status: true,
            message: "Insert successfully",
            data: response
        })
    }
    catch (error) {
        console.error(error);
        res.status(500).json({
            status: false,
            message: error.message,
            data: "Server issue"
        })
    }
}
英文:

the issue is in your controller file, you are exporting the function under the name post and importing it in your routes file as createBlog. To correct your code you should update your controller and rename the function as createBlog :

<!-- language: lang-js -->

const createPost = require(&quot;../models/post&quot;);

exports.createBlog = async (req,res) =&gt; {
    try {
        const {title,description} = req.body;
        const response = await createPost.create({title,description});

        res.status(200).json({
            status:true,
            message:&quot;Insert seccessfully&quot;,
            data:response
        })
    }
    catch(error) {
        console.error(err);
        res.status(500).json({
            status:false,
            message:error.message,
            data:&quot;Server issue&quot;
        })
    }
}

<!-- end snippet -->

答案3

得分: 0

The error message suggests that the issue is with the post method in your controller file. Specifically, it seems like createBlog in your routes/blogRoutes.js file is not correctly importing the controller function createBlog from your controllers/createBlog.js file.

In your controllers/createBlog.js file, the function is exported as exports.post. However, in your routes/blogRoutes.js file, you are importing it as const {createBlog} = require("../controllers/createBlog");. The key here is that you are importing createBlog, but the actual function in your controller file is called post.

英文:

The error message suggests that the issue is with the post method in your controller file. Specifically, it seems like createBlog in your routes/blogRoutes.js file is not correctly importing the controller function createBlog from your controllers/createBlog.js file.

In your controllers/createBlog.js file, the function is exported as exports.post. However, in your routes/blogRoutes.js file, you are importing it as const {createBlog} = require("../controlers/createBlog");. The key here is that you are importing createBlog, but the actual function in your controller file is called post.

huangapple
  • 本文由 发表于 2023年5月7日 20:50:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定