【发布时间】:2019-07-11 05:07:23
【问题描述】:
我有一个简单的 instagram 身份验证应用程序。在我对 instagram 进行身份验证并接收用户配置文件后,我想将用户名从服务器端发送到 reactjs 客户端。我尝试使用套接字 IO,但无法使其工作。
客户端
componentDidMount() {
const { socket, provider } = this.props
console.log('component did mount')
socket.on(provider, user => { //provider is a string e.g 'instagram'
//receives data and update state.
this.setState({user})
})
}
startAuth() { //onclick function that opens up new window for auth
const {provider} = this.props
const width = 600, height = 600
const left = (window.innerWidth / 2) - (width / 2)
const top = (window.innerHeight / 2) - (height / 2)
const url = `https://localhost:5000/${provider}`
return window.open(url, '',
`toolbar=no, location=no, directories=no, status=no, menubar=no,
scrollbars=no, resizable=no, copyhistory=no, width=${width},
height=${height}, top=${top}, left=${left}`
)
}
服务器端
//After successful authentication redirect here with username and provider as
//query string. Here I want to emit to my component and update component's state
app.get('/success', (req, res) => {
var provider = req.query.provider
var username = req.query.username
io.emit(provider, username); //this doesn't work
res.send('Auth to ' + provider + ' successful by ' + username)
})
我应该怎么做才能让服务器端发出的事件被内部组件DidMount()捕获?我没有收到任何错误消息。我什至不确定 /success 处发出的事件是否被触发。
Socket 连接工作正常,我做了下面的代码,它工作正常。
io.on('connection', (client) => {
client.on('subscribeToTimer', (interval) => {
console.log('client is subscribing to timer with interval', interval);
setInterval(() => {
client.emit('timer', new Date());
}, interval);
})
})
【问题讨论】:
-
您是否遇到任何错误?而不是套接字,对于上述用例,您可以将数据作为 /success 响应而不是套接字发送。
-
不,没有错误消息。我该如何发送这样的回复?你能带我过去吗?
标签: node.js reactjs express socket.io