[英]React - GET and POST requests with axios
In my application I need to GET
some data (for which I provide the native authtoken).在我的应用程序中,我需要
GET
一些数据(为此我提供了本机 authtoken)。
In the same event, however, I also need to POST
a second token to be consumed by a few endpoints, for external backend api calls.但是,在同一事件中,我还需要发布第二个令牌以供几个端点使用,用于外部后端
POST
调用。
How do I POST
this second token using my working code below using axios
?如何使用
POST
使用下面的工作代码axios
第二个令牌?
Should I extend Authorization bearer or simply POST
Spotify Token as string data?我应该扩展授权承载还是简单地将
POST
令牌作为字符串数据发布? How so?怎么会这样?
My code:我的代码:
getData(event) {
const {token} = this.props.spotifyToken
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/endpoint`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data.data)
})
.catch((error) => { console.log(error); });
};
For an async await applied to your code would look something like this.对于应用到您的代码的异步等待看起来像这样。
async getData(event) {
const {token} = this.props.spotifyToken
let getRes = await axios.get(`${process.env.URL}/endpoint` {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.localStorage.authToken}`
}
}
let postRes = await axios.post(`${process.env.URL}/endpoint` {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.localStorage.authToken}`
}
}
console.log(getRes.data.data);
console.log(postRes.data.data);
};
In this specific case, where a token is needed to fetch data at backend, I found that passing token at url is more suitable, like so:在这种特定情况下,需要令牌在后端获取数据,我发现在 url 传递令牌更合适,如下所示:
@endpoint.route('/endpoint/<select>/<user_id>/<token>', methods=['GET'])
def endpoint(name, user_id, token):
# business logic
and:和:
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/endpoint/${select}/${userId}/${this.props.spotifyToken}`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
otherwise, backend code would run twice, for POST and GET, which is not desired in my case.否则,后端代码将运行两次,用于 POST 和 GET,这在我的情况下是不需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.