Node.js fetch POST仅返回Express API服务器前端中的_id对象
我正在尝试制作一个React-Node.js应用程序进行实践。我在发送POST请求时遇到问题。当我在App.js中获取POST请求时,它只返回id。我希望它再返回3个值 当前对象Node.js fetch POST仅返回Express API服务器前端中的_id对象,node.js,reactjs,express,fetch,Node.js,Reactjs,Express,Fetch,我正在尝试制作一个React-Node.js应用程序进行实践。我在发送POST请求时遇到问题。当我在App.js中获取POST请求时,它只返回id。我希望它再返回3个值 当前对象 {u id:5a046d52bb5d37063b3c8b21} 理想物体 {u id:“59e9fed60fe8bf0d7fd4ac6e”,名称:“recipe1”,成分:“苹果”,描述:“切苹果”} 我应该如何正确地向req.body添加值?我引用了此解决方案,但它不适用于我的应用程序 index.js(node.j
{u id:5a046d52bb5d37063b3c8b21}
理想物体
{u id:“59e9fed60fe8bf0d7fd4ac6e”,名称:“recipe1”,成分:“苹果”,描述:“切苹果”}
我应该如何正确地向req.body添加值?我引用了此解决方案,但它不适用于我的应用程序
index.js(node.js)
App.js(react)
类应用程序扩展组件{
建造师(道具){
超级(道具);
this.handleSubmit=this.handleSubmit.bind(this);
}
handleSubmit(e){
e、 预防默认值();
获取(“/recipe”{
方法:“POST”,
正文:JSON.stringify({
名称:this.refs.name.value,
成分:this.refs.components.value,
描述:this.refs.descriptions.value
}),
标题:{“内容类型”:“应用程序/json”}
})
。然后((res)=>{
return res.json()
})
。然后((正文)=>{
控制台日志(“主体”+主体)
console.log(“结果”+this.refs.name.value)
})
}
render(){
返回(
菜谱
)
}
}
导出默认应用程序 服务器端更改:
app.post('/recipe', (req, res) => {
// log the body of the request, to make sure data is properly passed
console.log(req.body);
// use mongodb's insertOne instead of the deprecated save
db.collection('recipe').insertOne(req.body, (err, result) => {
if (err) return console.log(err);
// log the result of db insertion
console.log(result);
console.log('saved to database');
// send the freshly saved record back to the front-end
res.json(result);
});
});
前端更改:
class App extends Component {
constructor(props){
super(props);
// add state to hold recipe returned from POST call
this.state = {
recipe: null,
name: '',
ingredients: '',
descriptions: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const { name, ingredients, descriptions } = this.state;
fetch('/recipe', {
method: 'POST',
body: JSON.stringify({
name,
ingredients,
descriptions
}),
headers: {"Content-Type" : "application/json"}
})
// when call completes, it should return the newly created recipe object
// as it was saved in the DB - just store it into state
.then((recipe)=> {
this.setState({recipe});
});
// TODO: handle error case
}
render() {
// added a paragraph tag to display the ID of the freshly created recipe
// it's only displayed if recipe is not null or undefined
// further changes: turning inputs into controlled inputs
const { name, ingredients, descriptions } = this.state;
return (
<div className="App">
<h1>Recipe List</h1>
<form onSubmit={this.handleSubmit}>
<input
value={name}
type="text"
onChange={e => this.setState({ name: e.target.value })}
placeholder="name" />
<input
value={ingredients}
type="text"
onChange={e => this.setState({ ingredients: e.target.value })}
placeholder="ingredients" />
<input
value={descriptions}
type="text"
onChange={e => this.setState({ descriptions: e.target.value })}
placeholder="descriptions" />
<input type="submit"/>
{ recipe &&
<p>Saved ID: {this.state.recipe._id}</p>
}
</form>
</div>
);
}
}
export default App;
类应用程序扩展组件{
建造师(道具){
超级(道具);
//添加状态以保留从POST调用返回的配方
此.state={
配方:空,
名称:“”,
成分:'',
描述:“”
};
this.handleSubmit=this.handleSubmit.bind(this);
}
handleSubmit(e){
e、 预防默认值();
const{name,components,description}=this.state;
获取(“/recipe”{
方法:“POST”,
正文:JSON.stringify({
名称
成分,
描述
}),
标题:{“内容类型”:“应用程序/json”}
})
//当调用完成时,它应该返回新创建的recipe对象
//由于它保存在数据库中-只需将其存储到状态
.然后((配方)=>{
this.setState({recipe});
});
//TODO:处理错误案例
}
render(){
//添加了一个段落标记以显示新创建的配方的ID
//仅当配方不为null或未定义时才显示
//进一步的变化:将输入变为受控输入
const{name,components,description}=this.state;
返回(
菜谱
this.setState({name:e.target.value})}
占位符=“名称”/>
this.setState({components:e.target.value})
占位符=“成分”/>
this.setState({descriptions:e.target.value})}
占位符=“说明”/>
{配方&&
保存的ID:{this.state.recipe.\u ID}
}
);
}
}
导出默认应用程序;
进一步的更改:将所有三个文本输入都转换为受控输入(所有三个字段的值都在状态中跟踪,并在提交表单时传递给
fetch
。我很惊讶,考虑到POST方法服务器端只是以重定向结束,并且从不使用结果值,您会得到任何回复(可能包含您新创建的数据对象)。是否看到正在写入数据库的值?未添加值。每个对象仅包含id,如{u id:“5a0472c56f37cb06a4c8f54c”}]
但每次添加配方时,配方
集合中都有一个新条目,只有\u id
字段设置,对吗?控制台.log(req.body)
从app.post
中显示了什么?它显示了在8080上收听{u id:5a0472c56f37cb06a4c8f54c}保存到数据库
非常感谢您的回答!我尝试过,但除了_id之外,它没有添加任何数据。终端中的结果:CommandResult{result:{n:1,opTime:{ts:[Object],t:2},electionId:7fffff000000000000002,ok:1},连接:{domain:null,\u事件:{error:[Object],close:[Object],timeout:[Object],parseError:[Object]},…
@aaayumiconsole.log(req.body)
的输出是什么(在app.post('/recipe',…)
)?@aaayumi那么这就是你的问题所在,不知何故你传递的是空的/没有数据,这就解释了为什么数据库中的对象除了数据库自动创建的\u id
之外没有数据。@aaayumi在客户端的handleSubmit
方法中,尝试记录一个(或全部)在您试图传递的三个值中,即console.log(this.refs.name.value)
。请将该日志放在fetch
调用之前。@aaayumi我已更新了答案,将所有3个输入转换为受控输入,因为我怀疑使用refs可能存在问题。仅在前端进行了更改。
app.post('/recipe', (req, res) => {
// log the body of the request, to make sure data is properly passed
console.log(req.body);
// use mongodb's insertOne instead of the deprecated save
db.collection('recipe').insertOne(req.body, (err, result) => {
if (err) return console.log(err);
// log the result of db insertion
console.log(result);
console.log('saved to database');
// send the freshly saved record back to the front-end
res.json(result);
});
});
class App extends Component {
constructor(props){
super(props);
// add state to hold recipe returned from POST call
this.state = {
recipe: null,
name: '',
ingredients: '',
descriptions: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const { name, ingredients, descriptions } = this.state;
fetch('/recipe', {
method: 'POST',
body: JSON.stringify({
name,
ingredients,
descriptions
}),
headers: {"Content-Type" : "application/json"}
})
// when call completes, it should return the newly created recipe object
// as it was saved in the DB - just store it into state
.then((recipe)=> {
this.setState({recipe});
});
// TODO: handle error case
}
render() {
// added a paragraph tag to display the ID of the freshly created recipe
// it's only displayed if recipe is not null or undefined
// further changes: turning inputs into controlled inputs
const { name, ingredients, descriptions } = this.state;
return (
<div className="App">
<h1>Recipe List</h1>
<form onSubmit={this.handleSubmit}>
<input
value={name}
type="text"
onChange={e => this.setState({ name: e.target.value })}
placeholder="name" />
<input
value={ingredients}
type="text"
onChange={e => this.setState({ ingredients: e.target.value })}
placeholder="ingredients" />
<input
value={descriptions}
type="text"
onChange={e => this.setState({ descriptions: e.target.value })}
placeholder="descriptions" />
<input type="submit"/>
{ recipe &&
<p>Saved ID: {this.state.recipe._id}</p>
}
</form>
</div>
);
}
}
export default App;