【发布时间】:2018-03-05 06:12:19
【问题描述】:
每当我尝试向 nodejs express api 发送 post 请求时,它都会发送 400 错误的请求响应,所以我完全不知道如何弄清楚它 首先是从 m 向节点发送值的反应代码如下:
我的行动:
const addcat = (category) =>{
return {
type:'ADD_CAT',
category
}
}
export const saveCat = (catData = {}) => {
return dispatch => {
const {
_id = '',
catname = '',
cat_description = ''
}= catData
const category = {_id, catname, cat_description}
return fetch('http://localhost:8000/api/categories',{
method:'POST',
body:JSON.stringify(catData),
headers: {"Content-Type": "application/json"}
}).then(catData => dispatch(addcat(catData.category)))
}
}
我的减速机:
const catdefaultstate = []
export default (state=catdefaultstate, action) =>{
switch(action.type){
case 'Add_CAT':
return [
...state,
action.category
]
default:
return state
}
}
我发送请求的表单
import React from 'react'
// import React-dom from 'react-dom'
class Categoryform extends React.Component{
state = {
catname:'',
cat_description:''
}
handlechange = (e) => {
this.setState({
[e.target.name]:e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault();
if(!this.state.catname || !this.state.cat_description){
this.setState(() => ({error:"Enter valid name"}))
}else{
this.setState(()=>({error:''}))
this.props.onSubmit({
catname:this.state.catname,
cat_description: this.state.cat_description
})
}
}
render(){
return(
<div>
{this.state.error && <p>{this.state.error}</p>}
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="catname"
placeholder="Enter category name"
onChange={this.handlechange}
value={this.state.catname}
/>
<input
type="text"
name="cat_description"
placeholder="Enter category decription"
onChange={this.handlechange}
value={this.state.cat_description}/>
<button>Add category</button>
</form>
</div>
)
}
}
export default Categoryform
// and below is from where action called
import React from 'react'
import { connect } from 'react-redux'
import Categoryform from './catform.js'
import {saveCat} from '../../actions/cataction'
const Createcat = (props) => (
<div>
<h1>Category form</h1>
<Categoryform onSubmit = {(category)=>{
props.dispatch(saveCat(category))
props.history.push('/')
}}/>
</div>
);
export default connect()(Createcat)
我的 express 节点工作正常,只是反应端插入数据的问题
这是网络标签的图像 network tab
现在这是节点代码截图 where that extracting
【问题讨论】:
标签: javascript node.js reactjs react-redux