我正在尝试根据前端的请求获取一些数据;但是我的后端无法从URL获取查询。 req.query始终返回未定义。
此问题发生在... / routes / api / matches.js
当我尝试使用几乎相同的代码从... / routes / api / summoners.js获取路由时,我可以使用正确的查询参数轻松获得所需的数据。
此URL有效:http://localhost:5000/api/summoners/?region=tr&summonerName=Free+Bird;
但这不是 http://localhost:5000/api/matches/?accountId=msGjm4PwDSSMN5s_4EGni6e01RW5ChzbkS-Yb12LWJ8
这是不起作用的matchs.js:
const express = require("express");
const router = express.Router();
const { Kayn, REGIONS } = require("kayn");
const kayn = Kayn("MY_API_KEY")();
router.get("/", async (req, res) => {
try {
const accountId = req.query.accountId;
const { matches } = await kayn.Matchlist.by.accountID(accountId);
console.log(`${req.query}`);
console.log(`${req}`);
res.status(200).send(JSON.stringify(matches));
} catch (err) {
console.log(err.message);
}
});
module.exports = router;
console.log打印此代码未定义。
,这是有效的summoners.js:
const express = require("express");
const router = express.Router();
const { Kayn, REGIONS } = require("kayn");
const kayn = Kayn("MY_API_KEY")();
router.get("/", async (req, res) => {
const summoner = await kayn.Summoner.by
.name(req.query.summonerName)
.region(req.query.region);
res.status(200).send(JSON.stringify(summoner));
});
module.exports = router;
这是启动服务器的index.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
//Middleware
app.use(bodyParser.json());
app.use(cors());
const port = process.env.PORT || 5000;
const summoners = require("./routes/api/summoners");
const matches = require("./routes/api/matches");
app.use("/api/summoners", summoners);
app.use("/api/matches", matches);
app.listen(port, () => console.log(`Server started on ${port}`));