我首先创建了一个在客户端进行api调用的react应用,这很重要,因为它公开了API密钥。因此,我必须创建一个后端Express服务器来进行api调用。但是在客户端,我的react应用允许您键入一个随机的用户名(更改状态),以便进行api调用并获取该用户的信息。有没有办法将状态/道具从客户端转移到后端Express,以完成api调用?
这是快递代码:
const express = require('express');
const app = express();
const fetch = require('node-fetch');
app.get('/api/customers', (req, res) => {
fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/huhi?api_key=<MY_API_KEY>')
.then(res => res.json())
.then(result => res.json(result));
});
const port = 5000;
app.listen(port, () => console.log(`Server started on port ${port}`))
在fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/huhi?api_key=<MY_API_KEY>')
本节中,有一种方法可以将'by-name /'之后的用户名更改为reginald,doublelift,fakerr等(存储在客户端反应状态)。
示例
获取('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/reginald?api_key=
或
fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/doublelift?api_key=
或
fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/faker?api_key=
答案 0 :(得分:1)
这取决于您如何将用户名发送到API,以及您在快速应用程序中设置的主体解析中间件。
fetch(`uri/by-name/${req.params.username}`)
// OR
fetch(`uri/by-name/${req.query.username}`)
// OR
fetch(`uri/by-name/${req.body.username}`)
答案 1 :(得分:1)
一种解决方案-
// ...
app.get("/api/customers/:userId", (req, res)=>{
fetch(`https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/${req.params.userId}?api_key=<MY_API_KEY>`)
.then(res => res.json())
.then(result => res.json(result));
})
//...
fetch(`/api/customers/${this.state.username}`).then(users => this.setState(users))