req.body.content给出未定义-Express JS

时间:2018-11-01 03:35:40

标签: javascript node.js rest express

我是node&express的新手。我试图创建注释应用程序的示例API。

当我尝试通过使用POSTMAN创建新注释来测试API时,我的req.body.title和req.body.content值未定义。但是,当我尝试控制台req.body时,我得到以下信息:

 { '{"title": "Chemistry Note", "content": "Lorem ipsum note clasds"}': '' }

我正在使用Express,bodyParser,猫鼬的最新版本。

这是note.controller.js文件

exports.create = (req, res) => {

    console.log(req.body.title);
    // Validating request
    if(!req.body.content) {
        return res.status(400).send({
            message: "Note content cannot be empty"
        });
    }

    // Creating a Note
    const note = new Note({
        title: req.body.title || "Untitled Note",
        content: req.body.content
    });

    // Saving Note
    note.save()
        .then(data => {
            res.send(data);
        }).catch(err => {
            res.status(500).send({
                message: err.message || "Some error occurred while creating the Note."
            });
        });
};

这是server.js文件:

const express = require("express");
const bodyParser = require("body-parser");

// Creating Express Application
const app = express();

// Parse request of content-type - application/x-www-form-url-encoded
app.use(bodyParser.urlencoded({extended: true}));

// Parse request of content type - application/json
app.use(bodyParser.json());

const dbConfig = require("./config/database.config");
const mongoose = require("mongoose");

// Using native promises
mongoose.Promise = global.Promise;

// Connecting to Database
mongoose.connect(dbConfig.url, {
    useNewUrlParser: true
}).then(() => {
    console.log("Successfully connected to the database");
}).catch(err => {
    console.log("Could not connect to the database. Exiting now...", err);
    process.exit();
});

// Define a simple route
app.get('/', (req, res) => {
    res.json({"message": "Welcome to Note Application"});
});

// Require Notes routes
require("./app/routes/note.routes.js")(app);

// Listen for requests
app.listen(3000, () => {
    console.log("Listening on port 3000");
});

下面是note.model.js文件:

const mongoose = require("mongoose");

// Defining Schema
const NoteSchema = mongoose.Schema({
    title: String,
    content: String
}, {
    timestamps: true
});

// Creating Model with this schema
module.exports = mongoose.model('Note', NoteSchema);

下面是note.routes.js文件:

module.exports = (app) => {

    // Contains the methods for handling CRUD operations
    const notes = require("../controllers/note.controller.js");

    // Creating new Note
    app.post('/notes', notes.create);
};

请帮助,谢谢。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

{ '{"title": "Chemistry Note", "content": "Lorem ipsum note clasds"}': '' }, 
it's not a object you want. 
For this json your key is '{"title": "Chemistry Note", "content": "Lorem ipsum note clasds"}'. 
And its don't have any key like title, content.

Change above object to
{"title": "Chemistry Note", "content": "Lorem ipsum note clasds"}