gpt4 book ai didi

node.js - (意外使用 'location' )与 PubNub 进行 react

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:34 25 4
gpt4 key购买 nike

所以我尝试使用 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;

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

最佳答案

始终使用 SSL

location 对象(window的属性)在react/node中不像在浏览器中那样可用。 See this post on SO post更多细节。

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

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

关于node.js - (意外使用 'location' )与 PubNub 进行 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44793010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com