【问题标题】:Why POST request is not getting sent?为什么没有发送 POST 请求?
【发布时间】:2021-11-16 07:53:01
【问题描述】:

创建 CRUD 应用程序。我可以发送 GET 请求,但没有发送其他请求。

以下行导致错误。

await Book.create(req.body);

app.js

const express = require('express');
const connectDB = require('./config/db');
const books = require('./routes/api/book');

const app = express();

connectDB();

app.use('/api/books', books);

app.get('/', (req, res) => {
    res.send('<h1>Starter Code</h1>')
});

const port = process.env.PORT || 8082;

app.listen(port, () => {
    console.log(`Listening on port ${port}`);
})

routes/api/book.js

const express = require('express');
const router = express.Router();

// Load book model
const { Book } = require('../../models/Book');

// @route GET api/books/test
// @description tests books route
// @access Public
router.get('/test', (req, res) => {
    res.send('Book route testing!');
});

// @route GET api/books
// @description get all books
// @access Public
router.get('/', async (req, res) => {
    try {
        const books = await Book.find();
        res.json(books);
    } catch (error) {
        res.status(404);
        res.json({nobooksfound: 'No Books found'});
    }
});

// @route GET api/books/:id
// @description get single book by id
// @access Public
router.get('/:id', async (req, res) => {
    try {
        const book = await Book.findById(req.params.id);
        res.json(book);
    } catch (error) {
        res.status(404);
        res.json({ nobookfound: 'No Book Found' });
    }
});

// @route POST api/books
// @description add or save book
// @access Public
router.post('/', async (req, res) => {
    try {
        await Book.create(req.body);
        res.json({msg: 'Book added successfully'});
    } catch (error) {
        res.status(400);
        res.json({
            error: 'Unable to add this book'
        })
    }
    
});

// @route PUT api/books/:id
// @description update book
// @access Public
router.put('/:id', async (req, res) => {
    try {
        const book = await Book.findByIdAndUpdate(req.params.id, req.body);
        res.json({
            msg: 'Updated Successfully'
        })
    } catch (error) {
        res.status(400);
        res.json({
            error: 'Unable to update the Database'
        })
    }
});

// @route PUT api/books/:id
// @description delete book
// @access Public
router.delete('/:id', async (req, res) => {
    try {
        const book = await Book.findByIdAndRemove(req.params.id, req.body);
        res.json({msg: 'Book entry deleted successfully'});
    } catch (error) {
        res.status(404);
        res.json({error: 'No such book'})
    }
});

module.exports = router;

models/Book.js

const mongoose = require('mongoose');

const BookSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    author: {
        type: String,
        required: true
    },
    description: {
        type: String
    },
    published_date: {
        type: Date
    },
    publisher: {
        type: String
    },
    updated_date: {
        type: Date,
        default: Date.now
    }
});

module.exports = Book = mongoose.model('book', BookSchema);

【问题讨论】:

  • 您遇到的错误是什么?代码行是否执行但没有按预期工作,或者甚至没有达到?
  • 您的标题似乎不正确。正在发送 post 请求,服务器正在接收它,并且正在发生错误。
  • @ChristianFritz 该行正在执行,但随后进入 catch 块
  • 是的,@KevinB 你猜对了
  • Nikita,你说它进入了 catch 块,但在那个 catch 块中你打印错误?为什么不?这将是调试它的明显方法。

标签: node.js mongodb rest


【解决方案1】:

你告诉它等待。但等待什么。你必须创建一个等待的 Promise。

您需要在模型中的某个地方创建一个 Promise。

//here is an example so you can see the flow. I know it's mysql and not mongo, but a promise is a promis

pullWhiteList: async (phone) => {

        data = new Promise((resolve, reject) => {
            sql = "SELECT c.name AS client_name, w.* FROM api_whitelist w INNER JOIN api_client c ON w.client_id = c.client_id WHERE phone LIKE ? ORDER BY phone ASC LIMIT 10;";
            db.query(sql, [phone + '%'], (err, res, fields) => {
                if (err) {
                    resolve(err);
                } else {
                    resolve(res);
                }
            });
        })

        return await data;
    },

【讨论】:

  • 对于等待的猫鼬模型方法,这不是必需的。它确实支持异步/等待。
  • 很高兴知道。我不使用猫鼬,所以请好先生,请赐教我们一个答案。
  • 我的猜测是另一个答案是正确的,但没有错误信息,我们只能假设。
  • 是的。谢谢。
【解决方案2】:

错误是你没有使用 body-parser。将 app.js 代码替换为以下代码。

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

const connectDB = require('./config/db');
const books = require('./routes/api/book');

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

connectDB();

app.use('/api/books', books);

app.get('/', (req, res) => {
    res.send('<h1>Starter Code</h1>')
});

const port = process.env.PORT || 8082;

app.listen(port, () => {
    console.log(`Listening on port ${port}`);
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2023-02-13
    • 2014-12-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多