React: use axios to post state to MongoDB

心不动则不痛 提交于 2021-02-10 19:33:18

问题


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;

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

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

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()
    });
  });*/
});

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

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

Where did i do wrong?


回答1:


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

Installation

$ npm install body-parser

>

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

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



回答2:


Please use app.post in the server, currently you are creating a get endpoint you should first make a post endpoint to make a post request. Please also check https://expressjs.com/en/guide/routing.html



来源:https://stackoverflow.com/questions/52542908/react-use-axios-to-post-state-to-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!