Javascript 在react with redux/redux thunk中发布到mongoDB
模拟图书馆 显示数据库中的书籍(作者标题类型)以及添加书籍的功能 正在从我的react组件正确获取数据。Javascript 在react with redux/redux thunk中发布到mongoDB,javascript,reactjs,redux,redux-thunk,Javascript,Reactjs,Redux,Redux Thunk,模拟图书馆 显示数据库中的书籍(作者标题类型)以及添加书籍的功能 正在从我的react组件正确获取数据。 数据以实物形式传递给我的action creator,同样由reducer正确处理。 似乎我的异步thunk已正确设置为使用axios发出post请求。我正在通过get请求正确获取数据库中已经存在的书籍 我的路线似乎正在运行,因为我能够正确地添加一本书,并使用邮递员取回所有的书。同样,当从react组件中获取书籍时,我的书籍会正确显示 问题出在哪里?为什么我的post请求没有到达我的数据库
数据以实物形式传递给我的action creator,同样由reducer正确处理。
似乎我的异步thunk已正确设置为使用axios发出post请求。我正在通过get请求正确获取数据库中已经存在的书籍 我的路线似乎正在运行,因为我能够正确地添加一本书,并使用邮递员取回所有的书。同样,当从react组件中获取书籍时,我的书籍会正确显示 问题出在哪里?为什么我的post请求没有到达我的数据库 我的行为-- 我的减速机-- 错误-- 图书模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookSchema = new Schema({
title: {
type: String,
// required: true,
lowercase: true
},
author: {
type: String,
// required: true,
lowercase: true
},
genre: {
type: String,
// required: true,
lowercase: true
},
pages: {
type: Number
},
available: {
type: Boolean,
default: true
}
});
module.exports = Book = mongoose.model('book', BookSchema);
您可能需要在您的axios设置中支持完整的url主机,还请发布上下文的错误日志
axios
.post('/books', {
'title':title,
'author':author,
'genre':genre
})
.then(res => {
dispatch(addBookSuccess(res.data))
})
.catch(err => {
dispatch(addBookFailure(err.message))
})
post请求需要my
server.js中的键值主体解析器,我在下面缺少该解析器:
...
app.use(bodyParser.json());
...
这似乎并没有解决这个问题。你可以创建一个sandboxI,我会记录req.body,只得到[object]作为回报。我知道这引用了对象,但这一定是没有保存到数据库的原因,对吗?有关如何纠正此行为的任何信息?您正在使用的后端是什么?如果是expressjs,那么您需要安装主体解析器并访问req.body[“title”]、req.body[“author”]等。如果可能的话,创建一个沙盒在这个基础上工作,以前从未使用过沙盒。我已经添加了我的服务器文件和模型。
const mongoose = require("mongoose");
const express = require("express");
const bodyParser = require("body-parser");
const db = require('./config/db');
const Book = require('./models/book');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.route('/books')
.get((req, res) => {
Book.find({}).then(docs => res.json(docs))
})
.post((req, res) => {
let b = new Book({
title: req.body.title,
author: req.body.author,
genre: req.body.genre
})
b.save()
.then(doc => console.log(doc))
.catch(err => console.error(err))
res.json(req.body)
})
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookSchema = new Schema({
title: {
type: String,
// required: true,
lowercase: true
},
author: {
type: String,
// required: true,
lowercase: true
},
genre: {
type: String,
// required: true,
lowercase: true
},
pages: {
type: Number
},
available: {
type: Boolean,
default: true
}
});
module.exports = Book = mongoose.model('book', BookSchema);
axios
.post('/books', {
'title':title,
'author':author,
'genre':genre
})
.then(res => {
dispatch(addBookSuccess(res.data))
})
.catch(err => {
dispatch(addBookFailure(err.message))
})
...
app.use(bodyParser.json());
...