ReactJs,Express和Axios,将请求发送到服务器,然后响应客户端

时间:2018-06-28 11:15:19

标签: reactjs express post get request

我有一个问题,如何将“参数”值发送到快递服务器。从服务器到客户端的响应不会有什么大问题,因为我做了响应。我无法将数据发送到服务器。

这是我的server.js文件

const express = require('express');
const axios = require('axios');
const app = express();
const port = process.env.PORT || 5000;
const cors = require('cors');
var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/category', (req, res) => {
   axios.get(`https://newsapi.org/v2/${params}&language=pl&sortBy=publishedAt&apiKey=API`)
  .then(response =>{
      let articles = [];
      response.data.articles.map((article) =>{
          articles.push(article);
      })
  res.send({ articles});
});
})
app.listen(port, () => console.log(`Listening on port ${port}`));

这是我的app.js

  //make api request
  setApiKey = params => {



   this.setState(
    {
      apiKey: api,
   },
   this.makeApiRequest, 
  );
   return api;
  }
  

  //set state after request
  makeApiRequest = () =>{
      axios.get('/category')
      .then(response => {
        this.setState({articles: response.data.articles});
      })
  }
 
 
  //set new  api on input chnage
  switchOnInputChange=(event)=>{
     if(event.target.value.length >3) {
        let params = `everything?q=${event.target.value}`
        this.setApiKey(params);
        this.setState({headerText: "Popularne"},
        this.makeApiRequest,
      )
       }
     if (event.target.value.length < 3){
       this.setState({
        apiKey: apiTop, 
        headerText: "Popularne"
      },
      this.makeApiRequest,);
    }
  }
 
scrollOnBtnClick = () =>{
  this.smoothScrollTo(0, window.outerHeight, 1500);
  this.toggleNav();
}
  //change api on click
  switchCatOnClick = (event) =>{    
    let text  = event.target.innerText;
    let params = `top-headlines?country=us&category=${event.target.getAttribute("switch")}`
    this.setApiKey(params);
    this.smoothScrollTo(0, window.outerHeight, 1500);
    this.setText(text);
  }
  
 
   
 

  

如您所见,我想传递在单击或输入更改时创建的参数。

1 个答案:

答案 0 :(得分:0)

工作解决方案:

server.js

app.get('/category',  (req, res) => {

   axios.get(`https://newsapi.org/v2/${req.query.path}?country=${req.query.country}&category=${req.query.category}&apiKey=API_KEY`)
  
  .then(response =>{
      let articles = [];
      response.data.articles.map((article) =>{
          articles.push(article);
      })
  res.send({ articles});
});
})

app.js

 switchCatOnClick = (event) =>{
    let text  = event.target.innerText;
    let params = `path=top-headlines&country=pl&category=${event.target.getAttribute("switch")}`
    this.callApi(`/category?${params}`)
    .then(response => {
      this.setState({
        articles: response.articles
      });
    });
    this.smoothScrollTo(0, window.outerHeight, 1500);
    this.setText(text);
    this.scrollOnBtnClick();
    this.toggleNav
  }