【发布时间】:2021-12-24 08:41:04
【问题描述】:
当我将带有查询的端点 URL 直接粘贴到 axios.get() 中时,它会正确响应并且我可以看到返回的 json 对象。 (即 axios.get(http://localhost:3000/api/products/product_search?secretKey=${secret}&id=${blabla}))。但是,如果我使用 SummonerByNameUrl 方法调用 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%20Object]</pre>\n' +
'</body>\n' +
'</html>\n'
},
isAxiosError: true,
toJSON: [Function: toJSON]
代码: config.js
const summonerByNameUrl = (summonerName) => `${URL(hidden)}${summonerName}`;
module.exports = {
summonerByNameUrl
}
summoner.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
}
products.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;
app.js
...
app.use('/api/products', productsRouter);
...
【问题讨论】:
-
什么是
URL?它返回什么?如果是URL,那么你应该调用它的构造函数,即new URL()。 -
网址为:xxx.herokuapp.com 请求返回一个json对象。我尝试调用 new URL() 但它说它已经是一个 URL 对象。我将一个 URL 传递到 getSummonerByName()
-
你误解了我的评论。您的代码实际上具有
URL(hidden),而您的问题中既没有定义URL也没有定义hidden。我在问那些是什么以及它们做什么 -
哦,误会了。我自己隐藏了网址。这就是我写 URL(hidden) 的原因。它实际上是代码中的一个 URL,如:xxx.herokuapp.com
-
尽量不要让混淆看起来像实际代码,它会变得非常混乱
标签: node.js axios get get-request