【问题标题】:Axios Request Not Fetching TweetsAxios 请求未获取推文
【发布时间】:2017-10-26 08:49:51
【问题描述】:

我正在尝试创建一个使用 ReactJS 制作的小型 Web 应用程序,并且我正在尝试使用 Twitter API 获取推文,但是当我执行我的代码时出现此错误:

我正在使用 Axios 进行 HTTP 请求,这是我的 api.js 文件。

import axios from 'axios';

module.exports = {
  fetchTweets: (language) => {
      var config = {
        headers: {
          'Authorization': 'OAuth oauth_consumer_key="consumer_key",oauth_token="token",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1495723125",oauth_nonce="nonce",oauth_version="1.0",oauth_signature="signature"',
        }
      };

     var encodedURI = window.encodeURI('https://api.twitter.com/1.1/search/tweets.json?q='+ language +'&result_type=recent');

     return axios.get(encodedURI,config)
     .then(function(response){
        console.log(response)
    });
  }
}

推文组件

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import api from '../utils/api';

const SelectedLanguage = (props) =>{
  var languages = ['react', 'node'];

  return (
    <ul className="languages">
      {languages.map((lang, index) => {
        return (
          <li
            style   = { lang === props.selectedKeyword ? { color: '#d0021b'} : null }
            onClick = { () => props.onSelect(lang) }
            key     = { index }>
            {lang}
          </li>
        )
      })}
    </ul>
  )
}

SelectedLanguage.propTypes = {
  selectedKeyword: PropTypes.string.isRequired,
  onSelect: PropTypes.func.isRequired,
}

class ReactTweets extends Component {
  constructor(props){
    super(props);
    this.state = {
      selectedKeyword: 'react',
      tweets: null
    }
    this.updateLanguage = this.updateLanguage.bind(this);
  }

  componentDidMount() {
    this.updateLanguage(this.state.selectedKeyword);
  }

  updateLanguage(lang){
    this.setState(function() {
      return {
        selectedKeyword: lang,
        tweets: null,
      }
    });
    api.fetchTweets(lang)
      .then(tweets => {
        console.log(tweets);
      });
  }

  render() {
    return (
      <div>
        <SelectedLanguage
          selectedKeyword={this.state.selectedKeyword}
          onSelect={this.updateLanguage}
        />
      </div>
    );
  }
}

export default ReactTweets;

非常感谢您的帮助 :) 谢谢

【问题讨论】:

    标签: javascript reactjs twitter twitter-oauth


    【解决方案1】:

    由于 CORS,您将永远无法完成这项工作。您需要通过启用了 CORS 的服务器从 Twitter 获取数据,而单纯通过前端应用程序是不可能的。这仅在您尝试从中获取数据的服务器允许此类请求时才有效。

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2018-12-26
      • 2020-05-31
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 2019-04-05
      • 2019-11-22
      相关资源
      最近更新 更多