“发布”请求未更新数据并在NodeJS中给出错误

时间:2018-06-20 11:34:01

标签: node.js mongodb mean-stack

我是NodeJS的新手。我正在尝试制作一个与书店有关的简单API。

const express = require('express');
const bodyParser =  require('body-parser');
const app = express();
const mongoose = require('mongoose');

app.use(bodyParser.json());

Genre = require('./models/genre.js');
Book = require('./models/book.js');

mongoose.connect('mongodb://localhost/bookstore');
const db = mongoose.connection;

app.post('/api/genres', function(req, res) {
  const genre = req.body;
    Genre.addGenre(genre, function(err, genre) {
        if(err) {
            throw err;
        }
        res.json(genre);
    });
});

app.listen(3000);
console.log('Running on port 3000...');

这是genres.js

var mongoose = require('mongoose');

const genreSchema = mongoose.Schema({
    name:{
        type: String ,
        required: true
    },
    create_date:{
        type: Date,
        default: Date.now
    }
});

const Genre = module.exports = mongoose.model('Genre', genreSchema);
//Add Genre
module.exports.addGenre = function(genre, callback){
    Genre.create(genre, callback);
}

我尝试过RestEasy和Postman。获取请求成功,但不发送请求。当我发出请求时,它将在IDE中给出此错误。

  

ValidationError:类型验证失败:名称:路径name为   必填。

此外,当我检查MongoShell时,它不会为书籍和类型创建日期。

2 个答案:

答案 0 :(得分:0)

您没有使用请求中的流派来创建

module.exports.addGenre = function(genre, callback){
    Genre.create(genre, function (err, gen) {
         return callback(err, gen)
    })

}

答案 1 :(得分:0)

好的,我尝试了一下,您的代码确实对我有用,所以毕竟这可能只是CORS问题。

这是我发出测试请求的方式:

<html>
<head><script src="https://unpkg.com/axios/dist/axios.min.js"></script></head>
<body>
    <script>
        axios
            .post('http://localhost:3000/api/genres', { name: "my genre" })
            .then(response => {
                document.body.innerHTML = 
                    `<pre>${JSON.stringify(response.data, null, 4)}</pre>`;
            });
    </script>
</body>
</html>

这将调用来自localhost:80的请求,如果从另一个端口请求,则需要CORS标头 。尽管如此,我的控制台还是出现了大错误:

Failed to load http://localhost:3000/api/genres: Request header field 
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

意思是我错过了一个我认为我们不需要的CORS标头。抱歉,标题已更新:

app.use((req,res,next)=>{
    res.header("Access-Control-Allow-Headers", "Accept, Accept-Language, Content-Language, Content-Type");
    res.header("Access-Control-Allow-Origin", "*"); 
    next();
});

这是完整的完整代码,包括为我的index.html提供服务:

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

app.use(bodyParser.json());

Genre = require("./genre.js");

mongoose.connect("mongodb://localhost/bookstore");
const db = mongoose.connection;

app.get("/", function(req, res) {
  res.sendFile(path.resolve(__dirname, "index.html"));
});

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Headers", "Accept, Accept-Language, Content-Language, Content-Type");
  res.header("Access-Control-Allow-Origin", "*");
  next();
});

app.post("/api/genres", function(req, res) {
  const genre = req.body;
  Genre.addGenre(genre, function(err, genre) {
    if (err) {
      throw err;
    }
    res.json(genre);
  });
});

app.listen(3000);
console.log("Running on port 3000...");