通过redux / redux-thunk发布到mongoDB

时间:2019-04-19 16:29:47

标签: javascript reactjs redux redux-thunk

模拟图书馆 显示数据库中的书籍(作者标题类型)以及添加书籍的功能。

正在从我的react组件正确获取数据。
数据将以实物形式传递给我的动作创建者,并且同样被化简器正确处理。
似乎正确设置了我的异步thunk以使用axios发出发布请求。我正在使用get请求正确地获取数据库中已有的书籍。

我的路线似乎可以正常运行,因为我能够正确地添加一本书并使用邮递员来获取所有书籍。再说一遍,从我的react组件中取出后,我的书可以正确显示。

问题出在哪里?为什么我的发帖请求没有到达我的数据库?

我的动作-

export const fetchBooks = () => dispatch => {
    axios.get('/books')
        .then(res => dispatch({
            type: FETCH_BOOKS,
            payload: res.data
        })) 
}

export const addBook = ({ title, author, genre}) => dispatch => {
    dispatch(addBookStarted())
    axios
      .post('/books', {
        title, 
        author, 
        genre
      })
      .then(res => {
        dispatch(addBookSuccess(res.data))
      })
      .catch(err => {
          dispatch(addBookFailure(err.message))
      })
}


const addBookSuccess = book => ({
    type: ADD_BOOK_SUCCESS,
    payload: {
      ...book
    }
});

const addBookStarted = () => ({
    type: ADD_BOOK_STARTED
});

我的减速器-

const initialState = {
    books: [],
    error: null,
    loadinng: false
}

export default function(state = initialState, action) {
    switch(action.type) {
        case FETCH_BOOKS:
            return {
                ...state,
                books: action.payload
            }

        case ADD_BOOK_STARTED:
            return {
                ...state,
                loading: true
            }

        case ADD_BOOK_SUCCESS:
            return {
                ...state,
                loading: false,
                error: null,
                books: [...state.books, action.payload]
            }

        case ADD_BOOK_FAILURE:
            return {
                ...state,
                loading: false,
                error: action.payload.error
            }

        default: 
            return state
    }
}

错误-

{ ValidationError: book validation failed: title: Path `title` is required., aut
hor: Path `author` is required., genre: Path `genre` is required.
    at ValidationError.inspect (C:\Users\Leeko\documents\repos\libapp\backend\no
de_modules\mongoose\lib\error\validation.js:59:24)
    at formatValue (internal/util/inspect.js:526:31)
    at inspect (internal/util/inspect.js:194:10)
    at Object.formatWithOptions (util.js:90:12)
    at Console.(anonymous function) (console.js:204:15)
    at Console.warn (console.js:221:31)
    at b.save.then.catch.err (C:\Users\Leeko\documents\repos\libapp\backend\serv
er.js:34:31)
    at process.internalTickCallback (internal/process/next_tick.js:77:7)
  errors:
   { title:
      { ValidatorError: Path `title` is required.
          at new ValidatorError (C:\Users\Leeko\documents\repos\libapp\backend\n
ode_modules\mongoose\lib\error\validator.js:29:11)
          at validate (C:\Users\Leeko\documents\repos\libapp\backend\node_module
s\mongoose\lib\schematype.js:926:13)
          at C:\Users\Leeko\documents\repos\libapp\backend\node_modules\mongoose
\lib\schematype.js:979:11
          at Array.forEach (<anonymous>)
          at SchemaString.SchemaType.doValidate (C:\Users\Leeko\documents\repos\
libapp\backend\node_modules\mongoose\lib\schematype.js:935:19)
          at C:\Users\Leeko\documents\repos\libapp\backend\node_modules\mongoose
\lib\document.js:1941:9
          at process.internalTickCallback (internal/process/next_tick.js:70:11)
        message: 'Path `title` is required.',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'required',
        path: 'title',
        value: undefined,
        reason: undefined,
        [Symbol(mongoose:validatorError)]: true },

sever.js(路由)

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

3 个答案:

答案 0 :(得分:2)

在我的/// <summary> /// This method takes the input string and shifts all letter characters /// to the left (subtracts) by the amount specified in shiftAmount, so /// if shiftAmount = 1, then 'M' becomes 'L', and 'a' becomes 'z'. /// </summary> /// <param name="input">The input string to apply changes to</param> /// <param name="shiftAmount">A value from 0 to 25, used to shift the characters</param> /// <returns>The modified (shifted) string</returns> public static string ShiftText(string input, int shiftAmount) { if (input == null) return null; // Ensure shift is between 0 and 25 shiftAmount %= 26; var result = string.Empty; // Loop through input and update result with shifted letters foreach (var character in input) { if (!char.IsLetter(character)) { // If the character isn't a letter, don't change it result += character; } else { var newChar = (char) (character - shiftAmount); // Adjust newChar to stay within this character range if (newChar < (char.IsLower(character) ? 'a' : 'A')) newChar += (char) 26; result += newChar; } } return result; } 中,我缺少以下内容:

server.js

答案 1 :(得分:0)

您可能需要在axios设置中支持完整的URL主机,也请发布有关上下文的错误日志

答案 2 :(得分:0)

axios通话中的一个小变化

axios
      .post('/books', {
        'title':title, 
        'author':author, 
        'genre':genre
      })
      .then(res => {
        dispatch(addBookSuccess(res.data))
      })
      .catch(err => {
          dispatch(addBookFailure(err.message))
      })

发布请求需要键值主体解析器