简体   繁体   English

RESTfull 服务,Post 无法正确保存到 db

[英]RESTfull services, Post cannot save properly to db

RESTfull services, Post cannot save properly to db RESTfull 服务,Post 无法正确保存到 db

I have node+express+mongoose My model:我有 node+express+mongoose 我的模型:

var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var bookModel = new Schema({
title: { type: String },
author: { type: String },
genre: { type: String },
read:{ type: Boolean, default:false }   
});
module.exports = mongoose.model('Book', bookModel);

My App.js我的 App.js

var express = require('express'),
mongoose = require('mongoose'),
bodyParser = require('body-parser');

var db = mongoose.connect('mongodb://localhost/bookApi');
var Book = require('./models/bookModel');
console.log(Book);

var app = express();

var port = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

bookRouter = require('./Routes/bookRoutes')(Book);

app.use('/api/books', bookRouter);
/*app.use('/api/authors', authorRouter);*/

app.get('/', function (req, res) {
    res.send('welcome to my API!');
});


app.listen(port, function () {
    console.log('Gulp running on Port: ' + port);
});

My Routes:我的路线:

var express = require('express');


var routes = function(Book){
    var bookRouter = express.Router();

bookRouter.route('/')
    .post(function(req, res){
        var book = new Book(req.body);

        book.save();
        res.status(201).send(book);

    })
    .get(function (req, res) {
        var query = {};
        if(req.query.genre){
            query.genre = req.query.genre;
        }

        Book.find(query, function (err, books) {
            if(err)
                res.status(500).send(err);
            else
                res.json(books);
        });
    });
bookRouter.route('/:bookId')
    .get(function (req, res) {

        Book.findById(req.params.bookId, function (err, book) {
            if(err)
                res.status(500).send(err);
            else
                res.json(book);
        });
    })
    .put(function (req, res){
        Book.findById(req.params.bookId, function (err, book) {
            if(err)
                res.status(500).send(err);
            else
                book.title = req.body.title;
                book.author = req.body.author;
                book.genre = req.body.genre;
                book.read = req.body.read;
                book.save();
                res.json(book);
        });
            });

    return bookRouter;
};
module.exports = routes;

I'm using Postmant to test I can get all info, but when I'm trying to post something like我正在使用 Postmant 测试我可以获得所有信息,但是当我尝试发布类似

{"title":"WAR","genre":"Sience Fiction","author":"Wells","read":false}

I'm getting back body: {"_id":"5629377429d3c1088c0ebf37","read":false} So from book model only last param is in the body,我回来了 body: {"_id":"5629377429d3c1088c0ebf37","re​​ad":false} 所以从书本模型中只有最后一个参数在正文中,

Can you please just take a look if I'm missing something如果我遗漏了什么,你能不能看看

You could display what you received in your application on a POST method.您可以通过POST方法显示您在应用程序中收到的内容。 I mean: printing the content of the variable req.body .我的意思是:打印变量req.body的内容。 I guess that it's empty.我猜它是空的。

I think that you miss the Content-Type header when you did the call from Postman.我认为您在从 Postman 拨打电话时错过了Content-Type标头。 I reproduced your problem without the header and it works with the header.我在没有标题的情况下重现了您的问题,并且它适用于标题。 Here is the request I used to make your code works:这是我用来使您的代码正常工作的请求:

POST /api/books/ HTTP/1.1
Content-Type: application/json

{"title":"WAR","genre":"Sience Fiction","author":"Wells","read":false}

And the corresponding response:以及相应的响应:

HTTP/1.1 201 Created
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 111
ETag: W/"6f-25V+nQZe0YZPysuvDsoa5Q"
Date: Fri, 23 Oct 2015 07:34:43 GMT
Connection: keep-alive

{"__v":0,"title":"WAR","genre":"Sience Fiction","author":"Wells","_id":"5629e313074a746934d55f40","read":false}

In fact the body-parser module needs this hint to know how to process the content.事实上, body-parser模块需要这个提示才能知道如何处理内容。 If you want to support a default content type (I mean if the header isn't present - in fact, it should be there), you could add an Express middleware to set a content type in the request if any.如果您想支持默认内容类型(我的意思是如果标头不存在 - 事实上,它应该在那里),您可以添加一个 Express 中间件来设置请求中的内容类型(如果有)。

Otherwise, one small remark regarding your code.否则,关于您的代码的一个小评论。 You could update it to leverage callback within the save method:您可以更新它以利用save方法中的回调:

bookRouter.route('/')
  .post(function(req, res){
    var book = new Book(req.body);

    book.save(function(err, savedBook) {
      res.status(201).send(savedBook);
    });
  })

Hope it helps you, Thierry希望对你有帮助,蒂埃里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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