當我將帶有查詢的端點 URL 直接粘貼到 axios.get() 中時,它會正確回應并且我可以看到回傳的 json 物件。(即 axios.get(http://localhost:3000/api/products/product_search?secretKey=${secret}&id=${blabla}))。但是,如果我使用 senterByNameUrl 方法呼叫 url,它會在我發出請求時崩潰。我的代碼有什么問題?
崩潰報告:
...
data: '<!DOCTYPE html>\n'
'<html lang="en">\n'
'<head>\n'
'<meta charset="utf-8">\n'
'<title>Error</title>\n'
'</head>\n'
'<body>\n'
'<pre>Cannot GET /[object Object]</pre>\n'
'</body>\n'
'</html>\n'
},
isAxiosError: true,
toJSON: [Function: toJSON]
代碼:config.js
const summonerByNameUrl = (summonerName) => `${URL(hidden)}${summonerName}`;
module.exports = {
summonerByNameUrl
}
召喚師.js
const config = require('../config');
const axios = require('axios');
const getSummonerByName = async (summonerName) => {
const res = await axios.get(config.summonerByNameUrl(summonerName));
return res.data;
}
const summonerParser = async (req, res) => {
if(!req.query.secretKey)
return res.status(403).json({error: 'missing secret key.'})
let data = await getSummonerByName(req.query)
return res.status(200).json(data);
}
module.exports = {
getSummonerByName,
summonerParser
}
產品.js
var express = require('express');
var axios = require('axios')
var router = express.Router();
const summoner = require('../services/summoner');
router.get('/product_search', summoner.summonerParser)
module.exports = router;
應用程式.js
...
app.use('/api/products', productsRouter);
...
uj5u.com熱心網友回復:
你正在呼叫你的函式,getSummonerByName(req.query)從它之前的行中可以清楚地看出它req.query是一個物件而不是一個字串。當在字串背景關系中使用物件(如您的 URL)時,它們會變成“[object Object]”,因此會出現錯誤。
在這里進行一些猜測,但您似乎想將一些req.query資訊作為查詢引數轉發給 Axios 呼叫。試試這個...
const PRODUCT_SEARCH_URL = "http://localhost:3000/api/products/product_search"
const getSummonerByName = async ({ secretKey, id }) => {
const { data } = await axios.get(PRODUCT_SEARCH_URL, {
params: { secretKey, id }
})
return data
}
如果您有一個回傳基本 URL(即http://localhost:3000/api/products/product_search)的輔助函式,那么一定要在 Axios 呼叫中使用它而不是字串文字。
uj5u.com熱心網友回復:
req.query 是一個物件,而不是一個字串。
您可以嘗試映射 req.query 物件以生成字串。類似的東西:
Object.keys(req.query).map(key => {
return key '=' req.query[key]
}).join('&')
此代碼回傳這樣的字串:'id=1&name=test',因此您可以傳遞給端點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/356423.html
