gpt4 book ai didi

node.js - mongodb : fetch API POST request returns a strange response

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:17 24 4
gpt4 key购买 nike

我想使用 fetch API 向 mongodb 发送 POST 请求。使用 fetch API 成功实现了 GET 请求,但未能成功实现 POST 请求。

在控制台日志中,POST 请求返回奇怪的响应,如下所示:

{n: 1, opTime: {…}, electionId: "7fffffff0000000000000001", ok: 1}
electionId:"7fffffff0000000000000001"
n:1
ok:1
opTime:{ts: "6490526445679411201", t: 1}
__proto__:Object

我从来没有遇到过这个回复,我不知道这意味着什么......

我的代码如下。

服务器.js

app.post('/recipe', (req, res) => {
console.log(req.body); // this console.log returns empty object : {}

db.collection('recipe').insertOne(req.body, (err, result) => {
if (err) return console.log(err);
console.log('saved to database')
res.json(result);
});
});

index.js

class App extends Component {
constructor(props){
super(props);
this.state={
results: [],
name: '',
ingredients: '',
descriptions: '',
modal: false
}
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: { 'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'}
})
.then( res => res.json())
.then( res => console.log(res)); //this console.log returns strange response
}

render() {

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" onClick={this.toggle}/>
</form>
</div>
)
}
}

export default App;

感谢您提前提供的帮助,

最佳答案

mongoDB insertOne 返回成功与否的信息。如果你想获取插入的数据,试试这个。

db.collection('recipe').insertOne(req.body,(err, result)=>{
if (err) return console.log(err);
console.log('saved to database');
res.json(result.ops[0]);
});

关于node.js - mongodb : fetch API POST request returns a strange response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47396361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com