Dav*_*888 3 mongoose node.js express reactjs
我想知道有没有办法从客户端向后端API get Request传递一个参数。此时,我对所需的参数进行了硬编码(名称:“newName”)。
后端路由:
app.get('/api/get/beerWithComments', (req,res,next) =>{
Beer.findOne({name:'newName'}) //I want to pass the correct name, now it's hard coded.
.populate('comments').exec((err,beer) =>{
if(err) return next(err);
res.json(beer);
});
});
Run Code Online (Sandbox Code Playgroud)
我的行动方法:
export const fetchBeerWithComments =() => async dispatch => {
const res= await axios.get('/api/get/beerWithComments');
dispatch({type: FETCH_BEER_WITH_COMMENTS, payload : res.data });
}
Run Code Online (Sandbox Code Playgroud)
我想将参数传递到这里。但我不知道是否可以将参数传递到我的后端。
export const fetchBeerWithComments =(parameter) => async dispatch => {...
Run Code Online (Sandbox Code Playgroud)
name您可以在查询字符串中传递参数并使用req.querylike读取处理程序中的参数值
app.get('/api/get/beerWithComments', (req, res, next) =>{
var qname = req.query.name || "";
if(!qname.length) {
res.status(404).json({"msg": 'Invalid name in query string'});
res.end();
return;
}
Beer.findOne({name: qname}) //I want to pass the correct name, now it's hard coded.
.populate('comments').exec((err,beer) =>{
if(err) return next(err);
res.json(beer);
});
});
Run Code Online (Sandbox Code Playgroud)
从客户端调用 GET API 时,只需添加name具有相应值的查询字符串参数,它就应该按您的预期工作。例如 URL 将类似于
export const fetchBeerWithComments =(parameter) => async dispatch => {
const res= await axios.get('/api/get/beerWithComments?name=' + parameter);
dispatch({type: FETCH_BEER_WITH_COMMENTS, payload : res.data });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16468 次 |
| 最近记录: |