【问题标题】:Real-time listener doesn't work in PWA with Pusher实时侦听器在带有 Pusher 的 PWA 中不起作用
【发布时间】:2018-09-07 00:36:38
【问题描述】:

我正在尝试构建my first PWA。我设法做到了it,但是由于某种原因,推送功能不起作用。

我现在已经调试了几个小时,但我无法让它工作。我已经尝试过多次重建应用程序。

所以,我订阅了这个

 this.prices = this.pusher.subscribe('coin-prices');

那我就有这个功能了

  sendPricePusher(data) {
    console.log('Sending data from React')
    console.log(data)
    axios.post('/prices/new', {
      prices: data
    })
      .then(response => {
        console.log(response)
      })
      .catch(error => {
        console.log(error)
      })
  }

我每隔 10 秒从我的

调用一次上面的函数
componentDidMount()
setInterval(() => {
      axios.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,LTC&tsyms=USD')
        .then(response => {
          this.sendPricePusher(response.data)
        })
        .catch(error => {
          console.log(error)
        })
    }, 10000)

NodeJs 可以完美地处理它。我在开发控制台中看到 200。

app.post('/prices/new', (req, res) => {

    // Trigger the 'prices' event to the 'coin-prices' channel
    pusher.trigger( 'coin-prices', 'prices', {
        prices: req.body.prices
    });

    res.sendStatus(200);
})

由于某种原因,这段神奇的代码不起作用。

this.prices.bind('prices', price => {
  this.setState({ btcprice: price.prices.BTC.USD });
  this.setState({ ethprice: price.prices.ETH.USD });
  this.setState({ ltcprice: price.prices.LTC.USD });
}, this);

它应该重新创建状态并且值将被更新。

所以,我得出的结论是我的服务器代码有问题。我想在heroku上托管应用程序。我尝试编写不同的服务器变体,但它们似乎都不起作用。但是,我不能 100% 确定我的服务器是问题所在。你能看看我的服务器代码吗?这是我的 server.js 文件和a link 到 github 上的项目,以防问题不那么明显。 Pusher 似乎是一项很酷的技术。我想在我未来的项目中继续使用它,只需要了解如何。

// server.js
const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const app = express()
const Pusher = require('pusher')
const HTTP_PORT = process.env.PORT || 5000;

//initialize Pusher with your appId, key, secret and cluster
const pusher = new Pusher({
    appId: '593364',
    key: '8d30ce41f530c3ebe6b0',
    secret: '8598161f533c653455be',
    cluster: 'eu',
    encrypted: true
})

// Body parser middleware
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static("build"));

// CORS middleware
app.use((req, res, next) => {
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*')
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true)
    // Pass to next layer of middleware
    next()
})

// API route in which the price information will be sent to from the clientside
app.post('/prices/new', (req, res) => {
    // Trigger the 'prices' event to the 'coin-prices' channel
    pusher.trigger( 'coin-prices', 'prices', {
        prices: req.body.prices
    });
    res.sendStatus(200);
})


app.use((req, res) => {
    res.sendFile(path.join(__dirname + "/build/index.html"));
  });

app.listen(HTTP_PORT, err => {
    if (err) {
      console.error(err)
    } else {
        console.log('Server runs on ' + HTTP_PORT)
    }
  })

【问题讨论】:

    标签: node.js reactjs server progressive-web-apps pusher


    【解决方案1】:

    区分问题出在您的服务器还是 Pusher 的功能的一个好方法是使用虚拟数据分别测试代码的 Pusher 部分,以确保至少发布/订阅功能正常工作,即您已设置它符合预期。

    所以您可以在单独的文件中尝试以下操作:

    //publisher
    pusher.trigger( 'coin-prices', 'prices', {
            prices: dummyprices
    });
    
    
    //subscriber
    var prices = pusher.subscribe('coin-prices');
    prices.bind('prices', ({ price }) => {
      console.log(price);
    })
    

    假设您已正确初始化 Pusher SDK,这应该可以工作,如果是这样,那么 Pusher 方面就很好,您可以集中精力找出服务器中导致应用程序无法工作的原因。

    顺便说一句,在您现有的代码中,您可能想要更改:

    this.prices.bind('prices', price => {})
    

    this.prices.bind('prices', ({ price }) => {})
    

    希望这会有所帮助。

    【讨论】:

    • 感谢您的评论。所以,我测试了我的应用程序。问题是它没有响应我的频道。 this.prices.bind('prices', ({price}) => { this.setState({ btcprice: price.prices.BTC.USD }); this.setState({ ethprice: price.prices.ETH.USD } ); this.setState({ ltcprice: price.prices.LTC.USD }); }, this);我的应用程序将数据发送到我的节点服务器 - 一切都很好。我的节点服务器接收数据并用正确的数据触发“pusher.trigger”。但是,即使出于某种原因,我的应用程序也不会触发房间订阅。我订阅了频道,但它根本没有响应。
    • 我修好了!在我意识到问题出在我的推送器设置上后,我重新创建了实例。一切正常。所以,我回到我的代码,主要问题是我在推送器设置中使用了 app_id 而不是 key。非常感谢您的小单元测试。我一定会为我的下一个项目实时检查:))。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2023-03-30
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 2017-09-27
    • 2019-11-09
    相关资源
    最近更新 更多