Javascript 在 React Native 中使用带有 Fetch 的授权标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30203044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using an authorization header with Fetch in React Native
提问by Richard Kho
I'm trying to use fetchin React Native to grab information from the Product Hunt API. I've obtained the proper Access Token and have saved it to State, but don't seem to be able to pass it along within the Authorization header for a GET request.
我正在尝试fetch在 React Native 中使用从 Product Hunt API 中获取信息。我已经获得了正确的访问令牌并将其保存到 State,但似乎无法在 GET 请求的 Authorization 标头中传递它。
Here's what I have so far:
这是我到目前为止所拥有的:
var Products = React.createClass({
getInitialState: function() {
return {
clientToken: false,
loaded: false
}
},
componentWillMount: function () {
fetch(api.token.link, api.token.object)
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
this.setState({
clientToken: responseData.access_token,
});
})
.then(() => {
this.getPosts();
})
.done();
},
getPosts: function() {
var obj = {
link: 'https://api.producthunt.com/v1/posts',
object: {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.state.clientToken,
'Host': 'api.producthunt.com'
}
}
}
fetch(api.posts.link, obj)
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
})
.done();
},
The expectation I have for my code is the following:
我对我的代码的期望如下:
- First, I will
fetchan access token with data from my imported API module - After that, I will set the
clientTokenproperty ofthis.stateto equal the access token received. - Then, I will run
getPostswhich should return a response containing an array of current posts from Product Hunt.
- 首先,我将
fetch使用来自我导入的 API 模块的数据的访问令牌 - 之后,我会将 的
clientToken属性设置this.state为等于收到的访问令牌。 - 然后,我将运行
getPosts它应该返回一个包含一系列来自 Product Hunt 的当前帖子的响应。
I am able to verify that the access token is being received and that this.stateis receiving it as its clientTokenproperty. I am also able to verify that getPostsis being run.
我能够验证是否正在接收访问令牌并将this.state其作为其clientToken财产接收。我还能够验证getPosts正在运行。
The error I'm receiving is the following:
我收到的错误如下:
{"error":"unauthorized_oauth", "error_description":"Please supply a valid access token. Refer to our api documentation about how to authorize an api request. Please also make sure you require the correct scopes. Eg \"private public\" for to access private endpoints."}
{"error":"unauthorized_oauth", "error_description":"请提供有效的访问令牌。请参阅我们的 api 文档,了解如何授权 api 请求。还请确保您需要正确的范围。例如 \"private public\ " 用于访问私有端点。"}
I've been working off the assumption that I'm somehow not passing along the access token properly in my authorization header, but don't seem to be able to figure out exactly why.
我一直在假设我没有在我的授权标头中正确传递访问令牌,但似乎无法弄清楚确切原因。
采纳答案by Richard Kho
It turns out, I was using the fetchmethod incorrectly.
事实证明,我fetch错误地使用了该方法。
fetchexpects two parameters: an endpoint to the API, and an optional object which can contain body and headers.
fetch需要两个参数:API 的端点,以及可以包含正文和标头的可选对象。
I was wrapping the intended object within a second object, which did not get me any desired result.
我将预期的对象包装在第二个对象中,这没有得到任何想要的结果。
Here's how it looks on a high level:
这是它在高层次上的样子:
fetch('API_ENDPOINT', OBJECT)
.then(function(res) {
return res.json();
})
.then(function(resJson) {
return resJson;
})
I structured my object as such:
我这样构造我的对象:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Origin': '',
'Host': 'api.producthunt.com'
},
body: JSON.stringify({
'client_id': '(API KEY)',
'client_secret': '(API SECRET)',
'grant_type': 'client_credentials'
})
回答by Cody Moniz
Example fetch with authorization header:
使用授权标头获取示例:
fetch('URL_GOES_HERE', {
method: 'post',
headers: new Headers({
'Authorization': 'Basic '+btoa('username:password'),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: 'A=1&B=2'
});
回答by Marquistador
I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:
我遇到了同样的问题,我使用 django-rest-knox 作为身份验证令牌。事实证明,我的 fetch 方法没有问题,看起来像这样:
...
let headers = {"Content-Type": "application/json"};
if (token) {
headers["Authorization"] = `Token ${token}`;
}
return fetch("/api/instruments/", {headers,})
.then(res => {
...
I was running apache.
我正在运行 apache。
What solved this problem for me was changing WSGIPassAuthorizationto 'On'in wsgi.conf.
为我解决这个问题的是更改WSGIPassAuthorization为'On'in wsgi.conf。
I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config, I did this:
我在 AWS EC2 上部署了一个 Django 应用程序,我使用 Elastic Beanstalk 来管理我的应用程序,因此在django.config.
container_commands:
01wsgipass:
command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
回答by lilash sah
completed = (id) => {
var details = {
'id': id,
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch(markcompleted, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson, 'res JSON');
if (responseJson.status == "success") {
console.log(this.state);
alert("your todolist is completed!!");
}
})
.catch((error) => {
console.error(error);
});
};

