我试图在React Native中使用fetch从产品搜索API获取信息。我已经获得了适当的访问令牌,并已将其保存到状态,但似乎无法在授权报头中为GET请求传递它。

以下是我目前所了解到的:

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

我对代码的期望如下:

首先,我将从导入的API模块中获取带有数据的访问令牌 之后,我将设置这个的clientToken属性。状态使其与接收到的访问令牌相等。 然后,我将运行getPosts,它应该返回一个响应,其中包含Product Hunt的当前帖子数组。

我能够验证访问令牌正在被接收,这。state正在接收它作为clientToken属性。我还能够验证getPosts是否正在运行。

我收到的错误如下:

{"error":"unauthorized_oauth", "error_description":"请提供有效的访问令牌。关于如何授权api请求,请参阅我们的api文档。还请确保您需要正确的作用域。例如“private public”用于访问私有端点。"}

我一直在努力消除这样一个假设,即我在授权头中以某种方式没有正确地传递访问令牌,但似乎无法找出确切的原因。


结果是我错误地使用了fetch方法。

fetch接受两个参数:一个API端点,一个可选对象,可以包含body和header。

我在第二个对象中包装了我想要的对象,这并没有给我任何想要的结果。

以下是它在高层上的外观:

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

我的选项对象结构如下:

    var options = {  
      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'
      })
    }

使用授权头获取示例:

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

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

我有这个相同的问题,我使用django-rest-knox认证令牌。事实证明,我的fetch方法没有任何问题,它看起来是这样的:

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

我在运行apache。

为我解决这个问题的是在wsgi.conf中将WSGIPassAuthorization更改为“On”。

我在AWS EC2上部署了一个Django应用程序,我使用Elastic Beanstalk来管理我的应用程序,所以在Django中。配置,我这样做:

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

如果你正在使用承载令牌,下面的代码片段应该可以工作:

const token = localStorage.getItem('token')

const response = await fetch(apiURL, {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            'Authorization': `Bearer ${token}`, // notice the Bearer before your token
        },
        body: JSON.stringify(yourNewData)
    })