簡體   English   中英

貓鼬不發布與快遞服務器

[英]Mongoose does not post with express server

我正在嘗試貓鼬,並且做了這個小項目:

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');
});

模型/ 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;

但是,當我用Postman發布以下json時,它只顯示“正在發送..”,而在瀏覽器中則顯示無法發布Cannot POST /api/boeken ,並且不發布數據:

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

我究竟做錯了什么? 我在后台使用mongod.exe守護程序。

我可以在瀏覽器上訪問/ api

您必須結束對帖子的要求:

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. 
    });
});

另外,請確保您的客戶端將Content-Type標頭設置為application / json。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM