为什么快递中的保存功能不起作用?

时间:2020-01-19 07:18:13

标签: javascript node.js api express routes

这是我快递的第一天。我试图创建一条简单的路线,但是我的保存功能似乎不起作用。我尝试查看在stackoverflow上发布的类似问题,但未能成功。任何帮助将不胜感激。

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

//ROUTES

router.post('/', (req, res) => {
    const post = new Post({
        title: req.body.title,
        description: req.body.description
    })

    post.save()
    .then(data => {
        res.json(data);
    })
    .catch(err => {
        res.json(err);
    }); 


});

module.exports = router; 

这是我的模特。

const mongoose = require("mongoose");

const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    }
});

module.exports = mongoose.model('Posts',PostSchema);

app.js代码

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");


//IMPORT ROUTES
const postsRoute = require("./routes/posts");

//MIDDLEWARE - Function that always execute when routes are being hit.
app.use(bodyParser.json())
app.use('/posts', postsRoute)
//app.use('/users', usersRoute)

//ROUTES
app.get('/', (req, res) => {
    res.send("We are on home");
});

//CONNECT TO DB
mongoose.connect(
process.env.DB_CONNECTION, 
{ useNewUrlParser: true },
() => {
    console.log("DB Connected!!")
})

//How do we start listening to the server
app.listen(3000);

我的邮递员查询- My Postman query screenshot

邮递员回应- enter image description here

如果您需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:-1)

您的app.js应该是:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");


//MIDDLEWARE - Function that always execute when routes are being hit.
app.use(bodyParser.json())


   mongoose.connect(process.env.DB_CONNECTION, {  useNewUrlParser: true }, function(err) {
    if (err) {
        console.error('System could not connect to mongo server')
        console.log(err)
        process.exit()
    } else {
        console.log('System connected to mongo server')
    }
});


//ROUTES
app.get('/', (req, res) => {
    res.send("We are on home");
});

//IMPORT ROUTES
const postsRoute = require("./routes/posts");

app.use('/posts', postsRoute)


app.listen(3000);

还要在路由器中添加控制台日志以检查req.body:

router.post('/', (req, res) => {
    console.log('req.body===',req.body);
    ...
});