[英]Is there a way to transfer client-side React state/props to complete a backend express(api call)
I first created a react app that was making api calls on client side, which is a big no no since it exposes the API key.我首先创建了一个在客户端进行 api 调用的 react 应用程序,这是一个很大的禁忌,因为它公开了 API 密钥。 So I have to create a backend express server to make api calls.
所以我必须创建一个后端快速服务器来进行 api 调用。 However on client side, my react app allows you to type in a random username(which changes the state) in order to make an api call and get that users information.
但是在客户端,我的 React 应用程序允许您输入随机用户名(更改状态)以进行 api 调用并获取该用户信息。 Is there a way to transfer state/ props from client side to backend express to complete an api call?
有没有办法将状态/道具从客户端传输到后端 express 以完成 api 调用?
Here is the Express Code:这是快递代码:
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}`))
in this section fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/huhi?api_key=<MY_API_KEY>')
is there a way to change the username after 'by-name/' to reginald, doublelift, faker, etc(stored in the client-side react state).在本节中
fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/huhi?api_key=<MY_API_KEY>')
有没有办法在 'by -name/' 到 reginald、doublelift、faker 等(存储在客户端反应状态)。
example例子
fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/reginald?api_key=<MY_API_KEY>') fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/reginald?api_key=<MY_API_KEY>')
or或者
fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/doublelift?api_key=<MY_API_KEY>') fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/doublelift?api_key=<MY_API_KEY>')
or或者
fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/faker?api_key=<MY_API_KEY>') fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/faker?api_key=<MY_API_KEY>')
It depends on how you send the username to your API, and the body parsing middleware you set in your express application.这取决于您如何将用户名发送到 API,以及您在 express 应用程序中设置的正文解析中间件。
fetch(`uri/by-name/${req.params.username}`)
// OR
fetch(`uri/by-name/${req.query.username}`)
// OR
fetch(`uri/by-name/${req.body.username}`)
One of the solutions -解决方案之一——
// ...
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.