'Post' 请求不更新数据并在 NodeJS 中给出错误

'Post' request not updating the data and giving error in NodeJS

我是 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。获取请求成功,但 Post 请求没有任何内容。当我发出请求时,它在 IDE 中给出了这个错误。

ValidationError: Genre validation failed: name: Path name is required.

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

您没有使用请求中的类型来创建

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

}

好的,我试过了,你的代码对我有用,所以它可能只是 CORS-problems。

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

<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-headers 。尽管如此,我的控制台还是出现了很大的错误:

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-header 我认为我们不需要。抱歉,已更新 headers:

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