mongodb - 带有参数的axios获取请求不起作用
问题描述
我正在将参数传递给 axios 获取请求。它适用于邮递员,但不适用于我的代码。我不知道我在哪里犯了错误。
我只想要来自 db 的一个特定数据,但我正在接收集合中可用的所有数据。但是有了邮递员,我得到了想要的数据
后端路线:
router.get('/displayUser', (req,res) => {
const query = user = req.body ;
Services.find(query)
.exec((err, services) => res.json(services))
})
axios 调用:我尝试了两种不同的方法,但都不起作用
方法一:
getData: async function () {
const user = this.userId
console.log(user)
let res = await axios.get('http://localhost:5000/api/services/displayUser' , { params: { user }})
console.log(res.data);
}
方法二:
getData: async function () {
var data = JSON.stringify({"user":this.userId});
console.log(data)
var config = {
method: 'get',
url: 'http://localhost:5000/api/services/displayUser',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
当我在控制台中获取数据时,我得到了集合中可用的所有 3 个对象,而不是与用户 ID 相关的特定对象
但是在邮递员中它可以按要求工作
解决方案
我这样做如下:
- 当我需要得到时:
app.get('/detail/:id', function (req, res) {
//console.log(req.params.id);
var url=urlDetail + "/" + req.params.id;
axios.get(url)
.then(function (response) {
// result=response.data;
res.render('database', { title: 'Detail' , dbs: response.data ,Version:pjson.version});
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
//console.log("ici always");
});
});
- 当我需要发布时(req.body 是一个 json):
app.post('/carto/demande', function (req, res) {
let data;
console.log(req.params);
console.log(req.body);
var url=urlCartoDemande;
axios.post(url,req.body)
.then(function (response) {
data=response.data;
res.render('carto', { title : 'Demande' ,Version:pjson.version,mode:"resultat",data:data } );
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
});
推荐阅读
- javascript - 表格未提交正确的数据
- asp.net-core-mvc - 如何修复从 Postman 中的 PUT json 发送的空对象?
- c# - 删除事件不是从角度调用 get 方法调用
- r - 在 Stargazer 表中包含标准化系数
- c# - 如何使代码显示信息?
- javascript - 是什么 !vue/typescript 应用程序中的符号
- angular - 隐藏加载器之前的图像加载
- flutter - 带有firestore的streambuilder中的嵌套查询
- c# - SqlException:用户“”登录失败。在 IIS 8 中的 ASP.NET CORE 1.0.1 APP 上
- python-3.x - Python将文件从URL添加到本地文件中的文件