我对 JS 和反应比较陌生,我正在使用 Redux-Form 将一个简单的项目添加到我的 mongo db 中。我已经配置了表单,并且 API 是使用 db 连接定义的,但我认为我没有正确地在操作中构建我的代码,以便它以一种可以解释的方式发送数据。
具体来说,我在按下提交后看到了表单数据,但出现 500 错误。有人可以指出我适当地塑造我的 ajax 请求的方向,以便接收数据库帖子的可用数据吗?
新物品形式:
import React, { Component } from 'react'; import { fetchItems } from '../actions/index'; import {reduxForm} from 'redux-form'; import { createItem } from '../actions/index';
class NewItem extends Component {
render () {
const { fields: {name, category, description, image}, handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.props.createItem)}>
<h3>Add an Item</h3>
<div className="form-group">
<label>Item Name</label>
<input type="text" className="form-control" {...name} />
</div>
<div className="form-group">
<label>Category</label>
<input type="text" className="form-control" {...category} />
</div>
<div className="form-group">
<label>Description</label>
<textarea className="form-control" {...description} />
</div>
<div className="form-group">
<label>Image URL</label>
<input type="text" className="form-control" {...image} />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
)
}
}
export default reduxForm({
form: 'NewItemForm',
fields: ['name', 'category', 'description', 'image'] }, null, {createItem})(NewItem);
行动
export const FETCH_MY_ITEMS = 'FETCH_MY_ITEMS';
export const FETCH_SEARCH_ITEMS = 'FETCH_SEARCH_ITEMS';
export const CREATE_ITEM = 'CREATE_ITEM';
export const FETCH_ITEM = 'FETCH_ITEM';
export const DELETE_ITEM = 'DELETE_ITEM';
export function createItem (props) {
const request = $.post('/newItem', props).then(function (result){
return {
result
}
});
return {
type: CREATE_ITEM,
payload: request
};
}
表达 index.js
app.post("/newItem", function(req, res) {
var newItem = require('./server/api/new-item')(dbConnection);
newItem(req, res);
});
newItem 的 api 端点
var assert = require('assert');
//add new item to
module.exports = function (dbConnection) {
return function (req, res) {
var newItem = req.body.newItem;
newItem.user = req.session.userId;
newItem.createDate = new Date;
dbConnection.collection('items').insertOne(newItem, function (err, result) {
if (err) {
res.send("error: something bad happened and your item was not saved")
}
res.send("success-item-posted");
res.end();
})
}
};
process_params (/Users/mary/working-files/closet-redux/node_modules/express/lib/router/index.js:330:12) 在下一个 (/Users/mary/working-files/closet-redux/node_modules/express /lib/router/index.js:271:10) 立即。(/Users/mary/working-files/closet-redux/node_modules/express-session/index.js:432:7)