【问题标题】:mongodb : fetch API POST request returns a strange responsemongodb:获取 API POST 请求返回一个奇怪的响应
【发布时间】:2018-05-03 22:17:29
【问题描述】:

我想使用 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

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

我的代码如下。

server.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;

提前感谢您的帮助,

【问题讨论】:

  • 您是否尝试过将headers 添加为您在请求的网址之后传递的对象的一部分?
  • 对不起,什么是 p.o? @fshock
  • 很抱歉。编辑了问题
  • 没关系,你做到了
  • 没问题。许多与问题相关的 fetch API 是“标题”,所以我在阅读了 stackoverflow 中的其他答案后添加了它,尽管它不起作用..

标签: node.js mongodb reactjs express fetch-api


【解决方案1】:

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

【讨论】:

  • 谢谢。现在 console.log 返回带有 _id 的对象。 {_id: "5a1309995f82754b4c4baaa4"} _id : "5a1309995f82754b4c4baaa4" __proto__ : Object 我想知道为什么它不包含正文数据? @godsenal
  • mongodb api 不会给你插入的文档。您已经在 req.body 中获得了数据!如果需要,您只需要添加 _id。或者你可以用猫鼬代替。
  • 我检查了 Postman 和 mLab,它是空的,只有 id:{ "_id": "5a130d53fdbaa54b8a22af85" } 终端中的 req.body 也是空的。 listening on 8080 {} saved to database
  • 所以.. 这不是 mongodb 问题。你使用正文解析器吗?
猜你喜欢
  • 2020-03-23
  • 1970-01-01
  • 2020-08-10
  • 2018-03-13
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 2021-07-10
相关资源
最近更新 更多