2017-07-03 28 views
1

我試圖將一個URL參數從反應組件傳遞到一個單獨的文件中的數據庫查詢。下面是我試圖做的事情的細目:請求參數顯示爲undefined

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)我想從搜索表單那些PARAMS進入數據庫查詢

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; 
    } 
    }); 

}); 

謝謝,

+0

您可以顯示每個console.log的註銷內容嗎? – Geraint

回答

0

根據axios文檔,axios.get(url, [config])其中config可以通過請求發送數據,例如, params字段或data字段。 data字段對於GET請求無效。

您可以嘗試以下操作將params發送到後端。

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 
}) 
+0

這樣做!我意識到我也在req中使用body,但由於它是一個GET請求,所以無法工作。 – evanarb