简体   繁体   中英

why i am unable to make any request to my mongodb database from nodejs

I am trying make post request from nodejs api to mongodb it is not working neither it is showing any error.

Before trying this my mongodb server was not working so i installed it again after uninstalling it. Right now mongo is connected fine even my nodejs console says that database is connected.

I am trying make post request using postsman .

I do have installed mongoose, body-parser and express. I am unable to figure out what is wrong here. please help.

this is my code

routes/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;

model/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'))

This is how i am posting using postman

nodejserror

Problem is your route is not getting called. Why? because you never send a request to it. POSTMAN says cannot POST /api/posts . I think it is because you use

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

I think this should be the correct way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM