为什么我仍然会从api get请求中收到401(未经授权)错误?

时间:2018-08-24 18:14:25

标签: javascript reactjs api get axios

我有一个示例,尝试使用axios从频道中获取一些视频以响应并获取对api的请求。一切看起来不错,但是当编译时,出现控制台错误,指出:GET https://api.vimeo.com/channels/180097/videos/&key=*********** 401 (Authorization Required

访问令牌是我注册时生成的正确令牌。这是设置的代码:

import React, { Component } from 'react';
import axios from 'axios';

const API_KEY = '***********************';

class Apicall extends Component {

   componentDidMount() {
       this.getChannel();
   }

   getChannel() {
        axios.get(`https://api.vimeo.com/channels/180097/videos/&key=${API_KEY}`) 
    .then(res => {
        const videos = res.data.data.children.map(obj => obj.data);
        this.setState({videos});
      });
   }

   constructor(props) {
       super(props);

      this.state = {
        channel_id: '180097',
        data: [],
        videos: [],
        per_page: '5',
        paging: {
            first: '/channels/180097/videos?page=1',
            last: '/channels/180097/videos?page=3' 
        }
    }
    this.getChannel = this.getChannel.bind(this);
}

render(){
    return (
         <div className="container">
           <h1></h1>
           <ul>
               {this.state.videos.map(video => 
                  <li key={video.uri}></li>
               )}
           </ul>
         </div>
       );
    }
 }
 export default Apicall; 

为什么它仍然没有获得访问令牌?

1 个答案:

答案 0 :(得分:2)

您首先需要将https://api.vimeo.com/oauth/authorize/client标头设置为Authorization,向Basic Auth发出发布请求,您的用户名是您的应用程序client identifier,密码是{{1 }}。 your client secret这样。您还需要将Authentication: Basic base64(<client-identifier>:<client-secret>)设置为grant_type

您将收到类似的回复:

client_credentials

然后{ "access_token": "dd339558163d867d92f4616ca06<redacted>", "token_type": "bearer", "scope": "public private", "app": { "name": "test", "uri": "/apps/<app_id>" } } 可用于以下请求:

您将access_token标头设置为Authorization的情况下向https://api.vimeo.com/channels/180097请求

Axios将是这样的:

Authorization: Bearer <access_token>

当然,这花了我一段时间,因为vimeo api文档非常糟糕。

xhr中的邮递员出口:

axios.post('https://api.vimeo.com/oauth/authorize/client',
        { grant_type: 'client_credentials' },
        { headers: { Authorization: 'Basic btoa(<client-identifier>:<client-secret>)' } })

axios.get('https://api.vimeo.com/channels/180097',
    { headers: { Authorization: Bearer <access_token>' } })

var data = "grant_type=client_credentials";

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://api.vimeo.com/oauth/authorize/client");
xhr.setRequestHeader("Authorization", "Basic <insert_base64_of_client_id_and_client_secret>");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Postman-Token", "e13df60c-a625-411d-8020-a51086e60838");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.send(data);