简体   繁体   中英

Mongoose does not post with express server

I am experimenting with Mongoose and I have made this little project:

db.js

var db = mongoose.connect('mongodb://localhost/boeken', function(){
    console.log('mongoose connected');
});
module.exports = db;

Server.js

var express = require('express');
var bodyParser = require('body-parser');
var db = require('./db');
var Boek = require('./models/boeken');

var app = express();
app.use(bodyParser.json());

//1. Eenvoudige instructie
app.get('/api', function (req, res) {
    res.json({'Gebruik': 'voer een GET of POST-call uit naar /boeken'});
});

//2. POST-endpoint: nieuw boek in de database plaatsen
app.post('/api/boeken', function (req, res, next) {
    var boek = new Boek({
       titel: req.body.titel,
       auteur: req.body.auteur,
       ISBN: req.body.ISBN
    });
});

app.listen(3000, function () {
    console.log('server gestart op poort 3000');
});

models/boeken.js

var mongoose = require("mongoose");
var Boek = mongoose.model('Boek', {
   titel: {type: String, required: true},
   auteur: {type: String, required: true},
   ISBN: {type: String, required: true},
   date: {type: Date, required: true, default: Date.now()}
});
module.exports = Boek;

But when I post the following json with Postman it just says "Sending.." and in the browser it says Cannot POST /api/boeken and does not post the data:

{
"titel": "Hey",
"auteur": "You",
"ISBN": "1111"
}

What am I doing wrong? I am using mongod.exe Daemon in the background.

I am able to reach /api on the browser btw

You have to end the request for the post to work:

app.post('/api/boeken', function (req, res, next) {
    var boek = new Boek({
       titel: req.body.titel,
       auteur: req.body.auteur,
       ISBN: req.body.ISBN
    });
    boek.save((err, b) => {  
      res.status(201).send(b); // end the request. 
    });
});

Also, ensure your client is setting the Content-Type header to application/json.

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