React:使用axios将状态发布到MongoDB [英] React: use axios to post state to MongoDB

查看:49
本文介绍了React:使用axios将状态发布到MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过Express和Node with Axios将状态作为数据发布到MongoDB.

I am trying to post the states as data to MongoDB through Express and Node with Axios.

class App extends React.Component {
  constructor(props){
    super(props)

    this.state={
      items: [{
          desc:"Manage",
          price: 5000,
          purchased: false,
        },
        {
          desc:"Deliver",
          price: 2000,
          purchased: false,
        },
        {
          desc:"Market",
          price: 4000,
          purchased: false,
        }
      ],
      data:null,
      DisabledButton: true
    }
  }

  getAddedItems(){
    return this.state.items.filter(item => item.purchased)
  }

  componentDidMount() {
    this.callApi()
      .then(res => this.setState({ data: res[0].name}))
      .catch(err => console.log(err));
  }

  callApi = async () => {
    const response = await fetch('/test');
    const body = await response.json();
    console.log("body is" + body)
    if (response.status !== 200) throw Error(body.message);

    return body;
  };

  handleClick(desc){
    const newItems = this.state.items.slice()
    this.printItems(newItems)
    for(var item of newItems){
      if(item.desc === desc){
        item.purchased = !item.purchased
      }
    }
    this.printItems(newItems)

    this.setState({
      items: newItems
    })
  }

  printItems(items){
    console.log(items[0].purchased + "  " + items[1].purchased + " " + items[2].purchased)
  }

  handleSubmit(e){
    e.preventDefault();
    const added = this.getAddedItems()

    axios.post('/add', added)
      .then(res => console.log(res))
      .catch(err => console.log(err));
  }

  render()  {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to Shopping Center</h1>
        </header>
      <div>
        <div>
          {this.state.data}
        </div>
        <Service url={Product1} desc="Manage" alt="MA" purchased={this.state.items[0].purchased} thisClick={ (desc) => this.handleClick("Manage")} />
        <Service url={Product2} desc="Deliver" alt="DE" purchased={this.state.items[1].purchased} thisClick={ (desc) => this.handleClick("Deliver")}/>
        <Service url={Product3} desc="Market" alt="MR" purchased={this.state.items[2].purchased} thisClick={ (desc) => this.handleClick("Market")}/>
      </div>
      <button type="button" className="btn btn-primary" onClick={(e) => this.handleSubmit(e)}>
                    Added to Cart
      </button>
      </div>
    );
  }
}

export default App;

getAddedItems()返回状态中所有已购买 true items .

The getAddedItems() returns all the items whose purchased is true in the state.

在我的 handleSubmit(e)函数中,我使用 axios 发出带有"/add"

In my handleSubmit(e) function, i used axios to make a post request with url "/add"

在我的server.js中,我有以下代码处理发布请求:

In my server.js, i have the following code handeling the post request:

//Get a Post route
app.get('/add', (req, res) => {
  console.log(req.query)
  /*for (let item of req.query){
    console.log(item.desc)
    console.log(item.price)
  }*/
  /*MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("cart");
    var objs = req;
    dbo.collection("items").insertMany(objs, function(err, result) {
      if (err) throw err;
      console.log("Number of documents inserted: " + result.insertedCount);
      db.close()
    });
  });*/
});

我目前正在调试它,所以我注释掉了server.js中的大部分代码

I am currently debugging it, so I am comment out majority of the code in my server.js

req.query 应该已经收到我发送的数据,但是当我执行req.query时,它为空

Th req.query should have received the data i send from react, but when I do req.query, it is empty

我在哪里做错了?

推荐答案

要访问 req.body ,我们需要使用body-parser中间件,该中间件在处理程序之前解析中间件中的传入请求主体.

To access the req.body we need to use body-parser middleware which Parse incoming request bodies in a middleware before your handlers.

$ npm install body-parser

>

var app = require('express')();
var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json

这篇关于React:使用axios将状态发布到MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆