如何使用 React、Redux 和 Webpack 实现 Google API [英] How to implement Google API with React, Redux and Webpack

查看:71
本文介绍了如何使用 React、Redux 和 Webpack 实现 Google API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Google 日历事件添加到我的 React Redux 应用中.
我试过使用 googleapis 和 google-auth-library 但 webpack 抛出错误,因为 googleapis 是为运行服务器端而构建的,并且 bundle.js 是从客户端引用的.所以我阅读了一些关于这些错误的论坛,他们都指出使用 Google 的 js 客户端库 代替.

我了解如何在 java 或 php 应用程序中实现这一点(我老了……35 岁;)但我是 React Redux 的新手,我正在寻找实现这一点的最佳方法.

我正在尝试从我的 actions.js 中的日历中获取事件.我尝试在我的 html 标题中包含 <script src="https://apis.google.com/js/api.js"></script> 然后使用 gapi.load() 来自 actions.js.我还尝试创建一个 api.js 文件并使用 require('./api') 引用它.我还尝试使用 Node.js 快速入门指南中的 cli 命令获取 access_token,然后使用 axios 直接调用 Google API,但我得到了 403.我想我只是没有提供正确的标头,但这无论如何都不是最佳实践.

我的问题基本上是如何在遵守 Redux 标准的同时从我的 actions.js 文件中引用 Google 的 js 客户端库?

解决方案

尽管有一些非常好的正确答案,我还是要回答我自己的问题.@MattYao 回答了我的实际问题,即如何在我的 actions.js 文件中获取可供参考的 js 脚本.@Ethan Brown 给出了一个非常详细的答案,显示了一些极好的流动可能性.@realseanp 更改了范围,但答案有效.

我尝试了以上所有方法,它们都奏效了.

所以我不确定我做错了什么,但我终于能够通过添加 <script src="https://apis.google.com/js/api.js"></script> 到我的索引头.我正在使用 pug 所以它看起来像这样:

文档类型html头标题我的标题链接(rel='stylesheet' href='/static/css/main.css')链接(rel='stylesheet' href='/static/css/react-big-calendar.css')脚本(src='https://apis.google.com/js/api.js' type='text/javascript')身体div(id='应用程序')脚本(src='/static/bundle.js' type='text/javascript')

这是我的组件文件:

从 'react' 导入 React从 'react-big-calendar' 导入 BigCalendar;从时刻"导入时刻;从'react-redux'导入{连接}从 '../actions/actions' 导入 { fetchEvents }BigCalendar.momentLocalizer(时刻);@connect((商店) => {返回 {事件:store.events.events}})导出默认类 Calendar 扩展 React.Component{组件WillMount(){this.props.dispatch(fetchEvents())}使成为(){返回 (<div><大日历事件={this.props.events}startAccessor='startDate'endAccessor='endDate'样式={{高度:800}}/>

)}}

然后我就可以在我的 actions.js 文件中使用它

导出函数fetchEvents(){返回(调度)=>{函数开始(){//2. 初始化 JavaScript 客户端库.gapi.client.init({'apiKey':API_KEY,//如果不需要身份验证,则 clientId 和范围是可选的.'clientId':CLIENT_ID,'范围':'个人资料',}).那么(函数(){//3. 初始化并发出 API 请求.返回 gapi.client.request({'路径':'https://www.googleapis.com/calendar/v3/calendars/MY_EMAIL@gmail.com/events?timeMax=2017-06-03T23:00:00Z&timeMin=2017-04-30T00:00:00Z',})}).then( (响应) => {让事件 = response.result.items派遣({类型:'FETCH_EVENTS_FULFILLED',有效载荷:事件})}, 函数(原因){控制台日志(原因);});};//1. 加载 JavaScript 客户端库.gapi.load('客户端', 开始)}}

我必须公开我的日历才能以这种方式访问​​它.所以现在我要处理 oauth2 的东西:/

I'm trying to get google calendar events into my React Redux app.
I've tried using googleapis and google-auth-library but webpack is throwing errors because googleapis was built to run server side and bundle.js is referenced from client. So I've read a few forums about these errors and they all point to using Google's js client library instead.

I understand how to implement this in a java or php app (I'm old... 35 ;) but I'm new to React Redux and I'm looking for the best way to implement this.

I'm trying to fetch the events from my calendar in my actions.js. I tried including <script src="https://apis.google.com/js/api.js"></script> in my html header and then using gapi.load() from actions.js. I also tried creating a api.js file and referencing that with require('./api'). I also tried to use the cli commands from the Node.js Quickstart guide to get an access_token and then just use axios to call Google API directly but I'm getting a 403. I'm thinking I'm just not providing the proper headers but that wouldn't be best practice anyway.

My question is basically how do I reference Google's js client library from my actions.js file while adhering to Redux standards?

解决方案

I'm going to answer my own question despite some very good correct answers. @MattYao answered my actual question of how to get a js script available for reference in my actions.js file. @Ethan Brown gave a very detailed answer that showed some excellent flow possibilities. @realseanp changed the scope but a valid answer.

I tried all of the above and they worked.

So I'm not sure what I was doing wrong but I was finally able to access the gapi object from actions.js by just adding <script src="https://apis.google.com/js/api.js"></script> to my index head. I'm using pug so it looks like this:

doctype
html
    head
        title MyTitle
        link(rel='stylesheet' href='/static/css/main.css')
        link(rel='stylesheet' href='/static/css/react-big-calendar.css')
        script(src='https://apis.google.com/js/api.js' type='text/javascript')
    body
        div(id='app')
        script(src='/static/bundle.js' type='text/javascript')

Here is my component file:

import React from 'react'
import BigCalendar from 'react-big-calendar';
import moment from 'moment';
import { connect } from 'react-redux'

import { fetchEvents } from '../actions/actions'

BigCalendar.momentLocalizer(moment);
@connect((store) => {
    return {
        events: store.events.events
    }
})
export default class Calendar extends React.Component 
{
    componentWillMount() 
    {        
        this.props.dispatch(fetchEvents())
    }

    render() 
    {
        return (
            <div>
                <BigCalendar
                    events={this.props.events}
                    startAccessor='startDate'
                    endAccessor='endDate'
                    style={{height: 800}}
                />
            </div>
        )
    }
}

And then I was able to get this working in my actions.js file

export function fetchEvents() 
{
  return (dispatch) =>
  {
    function start() 
    {
      // 2. Initialize the JavaScript client library.
      gapi.client.init({
        'apiKey': API_KEY,
        // clientId and scope are optional if auth is not required.
        'clientId': CLIENT_ID,
        'scope': 'profile',
      }).then(function() {
        // 3. Initialize and make the API request.
        return gapi.client.request({
          'path': 'https://www.googleapis.com/calendar/v3/calendars/MY_EMAIL@gmail.com/events?timeMax=2017-06-03T23:00:00Z&timeMin=2017-04-30T00:00:00Z',
        })
      }).then( (response) => {
        let events = response.result.items
        dispatch({ 
          type: 'FETCH_EVENTS_FULFILLED',
          payload: events
        })
      }, function(reason) {
        console.log(reason);
      });
    };

    // 1. Load the JavaScript client library.
    gapi.load('client', start)
}}

I had to make my calendar public to access it this way. So now I'm going to work on the oauth2 stuff :/

这篇关于如何使用 React、Redux 和 Webpack 实现 Google API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆