【问题标题】:(Unexpected Use of 'location') React with PubNub(“位置”的意外使用)与 PubNub 反应
【发布时间】:2017-06-28 03:10:52
【问题描述】:

所以我正在尝试使用 React 和 Pubnub 以及 Node.JS 构建一个基于聊天的应用程序。整个应用程序的创建过程一切顺利,除了在以下代码行收到“意外使用位置错误”:

 Line 23: ssl: (location.protocol.toLowerCase() === 'https:'),    

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';
    import Messages from './Messages.js';
    import MessageHistory from './MessageHistory.js';
    import $ from 'jquery';
    import { BrowserRouter, Route, Link, NavLink, Switch } from 'react-router-dom';
    import Pubnub from 'pubnub';

    class App extends Component {
      constructor(props){
        super(props);
      this.state = {
            username: '',
            history: [],
      }
      this.sendMessage = this.sendMessage.bind(this);
    }
    componentDidMount() {
      this.Pubnub = Pubnub.init({
        publish_key: 'pub-redacted',
        subscribe_key: 'sub-redacted',
        ssl: (location.protocol.toLowerCase() === 'https:'),
      });
      this.Pubnub.subscribe({
        channel: 'Somerset',
        message: (message) => this.setState({
          history: this.state.history.concat(message)
        })
      })
    }
      sendMessage = (message) => {
        this.Pubnub.publish({
          channel: 'Somerset',
          message: message,
        })
      }
      render() {
        return (
          <BrowserRouter>
          <div className="App">
          <MessageHistory history={this.state.history} />
          <Messages username={this.state.username} sendMessage={this.sendMessage} />
          </div>
          </BrowserRouter>
        );
      }
            }
             export default App;

知道如何解决这个问题吗?

【问题讨论】:

  • @CraigConover 我的错克雷格!忘记回复了。将 SSL 设置为 true 就可以了!非常感谢!
  • 太好了 - 我将我的 cmets 移至官方答案。

标签: node.js reactjs websocket pubnub


【解决方案1】:

始终使用 SSL

location 对象(window 的属性)在 react/node 中不可用,就像在浏览器中一样。 See this post on SO post 了解更多详情。

但在初始化 Pubnub 对象时确实没有理由不使用 SSL。我建议只将其设置为 true,而不是使用 app 的协议来有条件地设置它。

this.Pubnub = Pubnub.init({
    publish_key: 'pub-redacted',
    subscribe_key: 'sub-redacted',
    // ssl: true
});

【讨论】:

    猜你喜欢
    • 2019-06-07
    • 2022-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多