【问题标题】:Request parameters showing as undefined请求参数显示为未定义
【发布时间】:2017-07-03 23:36:52
【问题描述】:

我正在尝试将一些 URL 参数从反应组件传递到单独文件中的数据库查询。以下是我正在尝试做的事情的细分:

TL;DR:当我尝试查询数据库时,api 请求似乎没有定义类别和城市字段。

1) 从搜索表单组件中获取搜索参数

<Link to={"tours"+"/" + this.state.category + "/" + this.state.city} >

2) 用户点击搜索,被重定向到搜索结果组件。一旦它们被重定向,这个函数就会被调用。正如我所料,道具正在使用搜索表单中的参数打印。

componentDidMount: function() {

// console.log(this.props.route);

console.log(this.props.params.category);
console.log(this.props.params.city);

var category = this.props.params.category;
var city = this.props.params.city;

helpers.viewTours(
{
  cat: category,
  cit: city
}
).then(function(response){
    var tours = response.data.length ? response.data[0].tour_title : 0;
    console.log("RESPONSE " + response);
    console.log("RESPONSE LENGTH " + response.data.length);
    console.log("RESULTS ", tours);
    //this.setState({trekList: response});
})

},

3) 使用包装函数 (helpers.viewTours) 我想将这些参数从搜索表单传递到数据库查询中

  viewTours: function(searchParams){

console.log("search params " + searchParams);
return axios.get("/tours/search", searchParams);

},

4) 该方法被调用,但参数未定义

  router.get("/search", function(req, res){
  var category = req.body.cat;
  var city = req.body.cit;
  console.log("tours cat " + category);
  console.log("tours cit " + city);
  Tour.find({}, function(error, doc) {
    // Send any errors to the browser
    if (error) {
      res.send(error);
    }
    // Or send the doc to the browser
    else {
      res.send(doc);
      //return doc;
    }
  });

});

谢谢,

【问题讨论】:

  • 您能否显示每个 console.log 的日志记录?

标签: reactjs express mongoose


【解决方案1】:

根据axios 文档,axios.get(url, [config]) 可以在其中配置请求发送数据,例如params 字段或 data 字段。 data 字段对于 GET 请求无效。

您可以尝试以下方法将参数发送到后端。

viewTours: function(searchParams){
   console.log("search params " + searchParams);
   return axios.get("/tours/search", { params: searchParams });
},

在服务器端,使用 req.params 从 url 获取参数。

router.get("/search", function(req, res){
   var category = req.params.cat;
   var city = req.params.city;
   // rest of code
})

【讨论】:

  • 做到了!我意识到我也在 req 中使用了 body,但是因为它是一个 GET 请求,所以这不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 2017-10-16
  • 2022-01-01
相关资源
最近更新 更多