【问题标题】:why i am unable to make any request to my mongodb database from nodejs为什么我无法从 nodejs 向我的 mongodb 数据库发出任何请求
【发布时间】:2019-04-20 16:07:38
【问题描述】:

我正在尝试从 nodejs api 向 mongodb 发出 post 请求,它既不工作也不显示任何错误。

在尝试此之前,我的 mongodb 服务器无法正常工作,因此我在卸载它后再次安装了它。现在 mongo 连接良好,即使我的 nodejs 控制台说数据库已连接。

我正在尝试使用postsman 发出帖子请求。

我确实安装了 mongoose、body-parser 和 express。 我无法弄清楚这里出了什么问题。请帮忙。

这是我的代码

路由/posts.js

const express = require('express');
const Post = require('../models/Post');
const router = express.Router();

router.post('/', (req, res, next) => {
    const post = new Post({
        _id: new mongoose.Types.ObjectId(),
        title: req.body.title,
        overview: req.body.overview,
        content: req.body.content,
    })
    post.save().then(result => {
        console.log(result);
        res.status(201).json({
            message: "Post created",
            createdPost: {
                _id: result._id,
                title: result.title,
                overview: result.overview,
                content: result.content,
            }
        })
    }).catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        })
    })
})
module.exports = router;

模型/Post.js

const mongoose = require('mongoose');

const postschema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    title: {
        type: String,
        required: true
    },
    overview: {
        type: String,
        required: true
    },
    content: {
        type: String,
        required: true
    },

},{timestamps: true});

module.exports = mongoose.model('Post', postschema);

index.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const posts = require('./routes/posts');
const app = express();

mongoose.connect('mongodb://localhost:27017/adi-site', { useNewUrlParser: true }).then(
    () => { console.log('database is connected') },
    err => { console.log('Can not connect to the database' + err) }
);


app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('api/posts', posts);

app.listen(8080, ()=>console.log('App is on 8080'))

这就是我使用邮递员发帖的方式

【问题讨论】:

  • 你怎么知道它不起作用?会发生什么?
  • 邮递员回复<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>Cannot POST /api/posts</pre> </body> </html>
  • @nos postman 没有给出例外响应。
  • 我认为你应该发布整个路由代码和正文解析器配置
  • console.log(result) 是否返回预期值?

标签: node.js mongodb


【解决方案1】:

问题是您的路线没有被调用。为什么?因为你从不向它发送请求。 POSTMAN 说不能 POST /api/posts 。我认为这是因为您使用

app.use('api/posts',  posts)

我认为这应该是正确的方式

app.use('/api/posts' , posts)

【讨论】:

  • 是的,这是肯定的。
猜你喜欢
  • 2016-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多