[英]Postman Get request works but not in browser- react/mongoose/express
[英]Unable to get the response of mongoose query inside Vuejs but works with postman request
服務器端首先是我的Api如何工作
searchPosts(params) {
return Api().get('search', params);
},
var postRouter = express.Router();
postRouter.get('/search', (req, res) => {
var db = req.db;
Post.find({ capacity: { $lte : req.body.capacity } }, function (error, q) {
if (error) { console.error(error); }
res.send({q})
})
})
有了這個,在我的快遞路線上我能夠對身體進行GET請求/搜索
{
"capacity":60
}
例如,並有一個按預期的工作響應
{
"q": [
{
"obj":"obj"
},
]
}
在我的.Vue文件中的網站端我在按鈕上的clic之后調用此函數
<v-btn
:disabled="!formIsValid"
flat
color="primary"
type="submit"
@click="searchPost">Search</v-btn>
methods: {
async searchPost() {
const response = await PostsService.searchPosts({
capacity: this.form.capacity,
equipments: this.createObjectFromArray(this.form.equipments),
date: this.form.date,
time: this.form.time,
});
console.log(response);
this.availableList = response.q;
},
郵遞員我正確地得到了一個q[]
數組,里面有我所有的過濾對象,但在chrome request
里面沒有q
對於我的Api日志,我對Postman沒有錯誤但是
message:
'Cast to number failed for value "undefined" at path "capacity" for model "Post"',
name: 'CastError',
...
在網上進行真正的測試
作為信息, this.availableList
在Data()
定義
data() {
const defaultForm = Object.freeze({
capacity: 0,
date: new Date().toISOString().substr(0, 10),
time: null,
equipments: [],
});
return {
form: Object.assign({}, defaultForm),
datePicker: false,
hourMenu: false,
availableList: [],
allList: [],
defaultForm,
};
},
確保Post模型中的容量字段包含type: number
。 如果您未在模型中明確聲明類型為數字,則默認情況下可能會假定您正在提交字符串值。
此外,由於您正在等待響應,因此還必須確保數據分配等待響應返回。 嘗試這個:
methods: {
async searchPost() {
const response = await PostsService.searchPosts({
capacity: this.form.capacity,
equipments: this.createObjectFromArray(this.form.equipments),
date: this.form.date,
time: this.form.time,
})
.then( response => {
console.log(response);
this.availableList = response.data.q;
}
)}
請注意,而不是response.q
我用response.data.q
。 我現在無法測試這個,所以如果它不起作用,請嘗試切換回response.q
。
我已經在我的vuejs文件中編輯了我的請求
async searchPost() {
const response = await PostsService.searchPosts({
capacity: this.form.capacity,
equipments: this.createObjectFromArray(this.form.equipments),
date: this.form.date,
time: this.form.time,
});
this.availableList = response.data;
},
在我的Api中我改變了它
searchPosts(params) {
return Api().get('search', { params });
},
我試圖通過在主體內傳遞參數而不是查詢字符串來運行get命令,這真是個傻瓜
所以,我相應地更新了我的get函數
postRouter.get('/search', (req, res) => {
var db = req.db;
Post.find({ capacity: { $lte : req.query.capacity } }, 'title description capacity equipments resa', function (error, q) {
if (error) { return res.status(500).send(error); }
res.send(q);
})
})
在req中找到我的find參數。 查詢 ,不再是身體
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.