为什么我的脚本要整个重启才能获取到新浪 weibo 的 access_token 呢?
完整的代码在 GitCafe 上, 我是想写个脚本把自己的微博下载下来:
http://gitcafe.com/jiyinyiyong/weibo-list/blob/master/server.coffee#code
用了 requst (0.9.5 and 0.10.0) 提示没 post 方法, 只好到网上抄了段 https POST 的代码了.
io.sockets.on 'connection', (s) ->
show 'connection'
s.on 'token', (token) ->
show 'hastoke', token
token = token.match(/code=([0-9a-f]+)/)[1]
path += "code=#{token}"
op =
host: 'api.weibo.com'
port: 443
path: path
method: 'POST'
headers:
'Content-Type': 'application/x-www-form-urlencode'
'Content-Length': 0
req = https.request op, (res) ->
data = ''
res.on 'data', (d) -> data += d
res.on 'end', ->
show data # <-- 下面输出的是这个
key = JSON.parse(data).access_token
s.emit 'key', key
req.on 'error', (e) -> console.log e
req.end()
问题是调试的时候我只刷新页面重新登录的时候, 会出现下面的错误:
{
"error":"invalid_grant",
"error_code":21325,
"request":"/oauth2/access_token",
"error_uri":"/oauth2/access_token",
"error_description":"invalid authorization code:d9c650f86f8ba7d****hide****b90b0code=4a5466d9b04b****hide****1434ee5bcode=3a54d125f7****hide****51cd60d690"
}
而我重启整个脚本, 再刷新页面的话就会返回正确的:
{
"access_token":"2.00GDymnBQXz******hide******AuST",
"remind_in":"86399",
"expires_in":86399,
"uid":"1651843872"
}
按说每次连接 socket 之后都会是新的 req 的, 为什么会出现这样的结果呢?