Using an authorization header with Fetch in React Native

时间:2015-05-12 23:16:37

标签: javascript oauth-2.0 react-native fetch-api

I'm trying to use sed -n '/ad[[:digit:]]\+/p' file in 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.

Here's what I have so far:

fetch

The expectation I have for my code is the following:

  1. First, I will 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(); }, an access token with data from my imported API module
  2. After that, I will set the fetch property of clientToken to equal the access token received.
  3. Then, I will run this.state which should return a response containing an array of current posts from Product Hunt.

I am able to verify that the access token is being received and that getPosts is receiving it as its this.state property. I am also able to verify that clientToken is being run.

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."}

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.

4 个答案:

答案 0 :(得分:146)

使用授权标头获取示例:

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'
 });

答案 1 :(得分:49)

事实证明,我错误地使用了fetch方法。

fetch需要两个参数:API的端点和可以包含正文和标题的可选对象。

我将目标对象包裹在第二个对象中,但没有得到任何预期的结果。

以下是它在高级别上的表现:

fetch('API_ENDPOINT', OBJECT)  
  .then(function(res) {
    return res.json();
   })
  .then(function(resJson) {
    return resJson;
   })

我构建了我的对象:

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'
  })

答案 2 :(得分:3)

我有同样的问题,我使用django-rest-knox进行身份验证令牌。事实证明,我的fetch方法没有任何问题,如下所示:

...
    let headers = {"Content-Type": "application/json"};
    if (token) {
      headers["Authorization"] = `Token ${token}`;
    }
    return fetch("/api/instruments/", {headers,})
      .then(res => {
...

我正在运行apache。

为我解决这个问题的方法是将WSGIPassAuthorization更改为'On'中的wsgi.conf

我在AWS EC2上部署了一个Django应用程序,我使用Elastic Beanstalk来管理我的应用程序,因此在django.config中,我这样做了:

container_commands:
  01wsgipass:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

答案 3 :(得分:0)

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);
        });
};