gpt4 book ai didi

javascript - Mongoose 不使用 Express 服务器发布

转载 作者:行者123 更新时间:2023-12-01 02:28:01 24 4
gpt4 key购买 nike

我正在尝试 Mongoose,并且做了这个小项目:

db.js

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

服务器.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 header 设置为 application/json。

关于javascript - Mongoose 不使用 Express 服务器发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48569516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com