React:使用axios将状态发布到MongoDB

时间:2018-09-27 18:14:19

标签: javascript mongodb reactjs axios

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

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()返回状态为itemspurchased的所有true

在我的handleSubmit(e)函数中,我使用axios来发送带有URL post的{​​{1}}请求

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

"/add"

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

//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() }); });*/ }); 应该已经收到我从react发送的数据,但是当我执行req.query时,它为空

我在哪里做错了?

2 个答案:

答案 0 :(得分:3)

要访问req.body,我们需要使用正文解析器中间件,该中间件在处理程序之前解析中间件中的传入请求正文。

安装

$ npm install body-parser

>

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

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

答案 1 :(得分:0)

请在服务器中使用app.post,当前正在创建一个get端点,您应该首先创建一个post端点来发出一个post请求。 另请检查https://expressjs.com/en/guide/routing.html