node.js - 用node做微信开发后台,获取access_token报错
迷茫
迷茫 2017-04-17 15:05:26
0
3
563

按照网上教程写的,但是貌似坑比较多,新手不知道哪里出错了,只知道是给一个没有定义的东西挂在属性什么什么的,下面贴出代码,如果不全,我继续贴。
报错:

这是目录结构:

下面是g.js

        'use strict'
        var sha1 = require('sha1');
        var Promise = require('bluebird');
        var request = Promise.promisify(require('request'));
        var prefix = 'https://api.weixin.qq.com/cgi-bin/';
        var api = {
            accessToken:prefix+'token?grant_type=client_credential'
        }
        function Wechat(opts) {
            var that = this;
            this.appID = opts.appID;
            this.appSecret = opts.appSecret;
            this.getAccessToken = opts.getAccessToken;
            this.saveAccessToken = opts.saveAccessToken;
            this.getAccessToken()
              .then(function (data) {
                try {
                    data = JOSN.parse(data);
                }
                catch(e) {
                    return that.updateAccessToken();
                }
                if (that.isValidAccessToken(data)) {
                    Promise.resolve(data);
                }
                else {
                    return that.updateAccessToken();
                }
              })
              .then(function (data) {
                that.access_token = data.access_token;
                that.expires_in = data.expires_in;
                that.saveAccessToken(data);
              })
        }
        Wechat.prototype.isValidAccessToken = function (data) {
            if (!data || !data.access_token || !data.expires_in) {
                return false;
            }
            var access_token = data.access_token;
            var expires_in = data.expires_in;
            var now = (new Date().getTime())
        
            if (now < expires_in) {
                return true;
            }else {
                return false;
            }
        }
        Wechat.prototype.updateAccessToken = function () {
            var appID = this.appID;
            var appSecret = this.appSecret;
            var url = api.accessToken + '&appid=' + appID + '&secret=' + appSecret;
            return new Promise(function (resolve, reject) {
                request({url: url, json: true}).then(function (response) {
                    var data = response[1];
                    var now = (new Date().getTime());
                    var expires_in = now + (data.expires_in - 20) * 1000;
                    data.expires_in = expires_in;
                    resolve(data);
                })
            })
        }
        module.exports = function (opts) {
            var wechat = new Wechat(opts);
            return function *(next) {
                console.log(this.query)
                var token = opts.token;
                var signature = this.query.signature;
                var nonce = this.query.nonce;
                var timestamp = this.query.timestamp;
                var echostr = this.query.echostr;
                var str = [token, timestamp, nonce].sort().join('');
                var sha = sha1(str);
                if (sha === signature) {
                    this.body = echostr + '';
                }
                else {
                    this.body = 'wrong';
                }
            }
        }
        

util.js:

    'use strict'
    var fs = require('fs');
    var Promise = require('bluebird');
    exports.readFileAsync = function (fpath, encoding) {
        return new Promise(function (resolve, reject) {
            fs.readFile(fpath, encoding, function (err, content) {
                if (err) reject(err);
                else resolve(content);
            })
        })
    }
    exports.writeFileAsync = function (fpath, content) {
        return new Promise(function (resolve, reject) {
            fs.writeFile(fpath, content, function (err) {
                if (err) reject(err);
                else resolve();
            })
        })
    }

app.js:

'use strict'
var Koa = require('koa');
var path = require('path');
var util = require('./libs/util');
var wechat = require('./wechat/g');
var wechat_file = path.join(__dirname,'./config/wechat.txt');
var config = {
    wechat: {
        appID: 'wxf959acc9ef3df3df',
        appSecret: 'a5eaa93a1f0b75e692c0fb88f8ecdd37',
        token: 'wuwei',
        getAccessToken: function () {
            return util.readFileAsync(wechat_file);
        },
        saveAccessToken: function (data) {
            data = JSON.stringify(data);
            return util.writeFileAsync(wechat_file, data);
        }
    }
}
var app = new Koa();
app.use(wechat(config.wechat))
app.listen(80);
console.log('listening:80');

response:

E:\慕课网\7天搞定Node.js微信公众号开发\wechat>node app
listening:80
data----- IncomingMessage {
  _readableState:
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: [],
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: true,
     ended: true,
     endEmitted: true,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: false,
  domain: null,
  _events:
   { end: [ [Function: responseOnEnd], [Function], [Function], [Function] ],
     close: [ [Function], [Function] ],
     data: [Function],
     error: [Function] },
  _eventsCount: 4,
  _maxListeners: undefined,
  socket:
   TLSSocket {
     _tlsOptions:
      { pipe: null,
        secureContext: [Object],
        isServer: false,
        requestCert: true,
        rejectUnauthorized: true,
        session: undefined,
        NPNProtocols: undefined,
        requestOCSP: undefined },
     _secureEstablished: true,
     _securePending: false,
     _newSessionPending: false,
     _controlReleased: true,
     _SNICallback: null,
     servername: null,
     npnProtocol: undefined,
     authorized: true,
     authorizationError: null,
     encrypted: true,
     _events:
      { close: [Object],
        end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        secure: [Function],
        free: [Function: onFree],
        agentRemove: [Function: onRemove],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener] },
     _eventsCount: 9,
     _connecting: false,
     _hadError: false,
     _handle: null,
     _parent: null,
     _host: 'api.weixin.qq.com',
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     domain: null,
     _maxListeners: undefined,
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: true,
        ended: true,
        finished: true,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: true,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: false,
     allowHalfOpen: false,
     destroyed: true,
     bytesRead: 319,
     _bytesDispatched: 195,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: undefined,
     _server: null,
     ssl: null,
     _requestCert: true,
     _rejectUnauthorized: true,
     parser: null,
     _httpMessage:
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 4,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'GET /cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37 HTTP/1.1\r\nhost: api.weixin.qq.com\r\naccept: application/json\r\nC
nnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        method: 'GET',
        path: '/cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
        parser: null,
        res: [Circular] },
     read: [Function],
     _consuming: true,
     _idleNext: null,
     _idlePrev: null,
     _idleTimeout: -1 },
  connection:
   TLSSocket {
     _tlsOptions:
      { pipe: null,
        secureContext: [Object],
        isServer: false,
        requestCert: true,
        rejectUnauthorized: true,
        session: undefined,
        NPNProtocols: undefined,
        requestOCSP: undefined },
     _secureEstablished: true,
     _securePending: false,
     _newSessionPending: false,
     _controlReleased: true,
     _SNICallback: null,
     servername: null,
     npnProtocol: undefined,
     authorized: true,
     authorizationError: null,
     encrypted: true,
     _events:
      { close: [Object],
        end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        secure: [Function],
        free: [Function: onFree],
        agentRemove: [Function: onRemove],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener] },
     _eventsCount: 9,
     _connecting: false,
     _hadError: false,
     _handle: null,
     _parent: null,
     _host: 'api.weixin.qq.com',
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     domain: null,
     _maxListeners: undefined,
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: true,
        ended: true,
        finished: true,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: true,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: false,
     allowHalfOpen: false,
     destroyed: true,
     bytesRead: 319,
     _bytesDispatched: 195,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: undefined,
     _server: null,
     ssl: null,
     _requestCert: true,
     _rejectUnauthorized: true,
     parser: null,
     _httpMessage:
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 4,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'GET /cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37 HTTP/1.1\r\nhost: api.weixin.qq.com\r\naccept: application/json\r\nC
nnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        method: 'GET',
        path: '/cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
        parser: null,
        res: [Circular] },
     read: [Function],
     _consuming: true,
     _idleNext: null,
     _idlePrev: null,
     _idleTimeout: -1 },
  httpVersionMajor: 1,
  httpVersionMinor: 1,
  httpVersion: '1.1',
  complete: true,
  headers:
   { connection: 'close',
     'content-type': 'application/json; encoding=utf-8',
     date: 'Thu, 20 Oct 2016 09:40:53 GMT',
     'content-length': '175' },
  rawHeaders:
   [ 'Connection',
     'close',
     'Content-Type',
     'application/json; encoding=utf-8',
     'Date',
     'Thu, 20 Oct 2016 09:40:53 GMT',
     'Content-Length',
     '175' ],
  trailers: {},
  rawTrailers: [],
  upgrade: false,
  url: '',
  method: null,
  statusCode: 200,
  statusMessage: 'OK',
  client:
   TLSSocket {
     _tlsOptions:
      { pipe: null,
        secureContext: [Object],
        isServer: false,
        requestCert: true,
        rejectUnauthorized: true,
        session: undefined,
        NPNProtocols: undefined,
        requestOCSP: undefined },
     _secureEstablished: true,
     _securePending: false,
     _newSessionPending: false,
     _controlReleased: true,
     _SNICallback: null,
     servername: null,
     npnProtocol: undefined,
     authorized: true,
     authorizationError: null,
     encrypted: true,
     _events:
      { close: [Object],
        end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        secure: [Function],
        free: [Function: onFree],
        agentRemove: [Function: onRemove],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener] },
     _eventsCount: 9,
     _connecting: false,
     _hadError: false,
     _handle: null,
     _parent: null,
     _host: 'api.weixin.qq.com',
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     domain: null,
     _maxListeners: undefined,
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: true,
        ended: true,
        finished: true,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: true,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: false,
     allowHalfOpen: false,
     destroyed: true,
     bytesRead: 319,
     _bytesDispatched: 195,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: undefined,
     _server: null,
     ssl: null,
     _requestCert: true,
     _rejectUnauthorized: true,
     parser: null,
     _httpMessage:
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 4,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'GET /cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37 HTTP/1.1\r\nhost: api.weixin.qq.com\r\naccept: application/json\r\nC
nnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        method: 'GET',
        path: '/cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
        parser: null,
        res: [Circular] },
     read: [Function],
     _consuming: true,
     _idleNext: null,
     _idlePrev: null,
     _idleTimeout: -1 },
  _consuming: true,
  _dumped: false,
  req:
   ClientRequest {
     domain: null,
     _events:
      { socket: [Object],
        response: [Function: bound ],
        error: [Function: bound ],
        drain: [Function] },
     _eventsCount: 4,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: true,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: false,
     sendDate: false,
     _removedHeader: {},
     _contentLength: 0,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: undefined,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 9,
        _connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'api.weixin.qq.com',
        _readableState: [Object],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        destroyed: true,
        bytesRead: 319,
        _bytesDispatched: 195,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1 },
     connection:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: undefined,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 9,
        _connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'api.weixin.qq.com',
        _readableState: [Object],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        destroyed: true,
        bytesRead: 319,
        _bytesDispatched: 195,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1 },
     _header: 'GET /cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37 HTTP/1.1\r\nhost: api.weixin.qq.com\r\naccept: application/json\r\nConn
ction: close\r\n\r\n',
     _headers: { host: 'api.weixin.qq.com', accept: 'application/json' },
     _headerNames: { host: 'host', accept: 'accept' },
     _onPendingData: null,
     agent:
      Agent {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        defaultPort: 443,
        protocol: 'https:',
        options: [Object],
        requests: {},
        sockets: [Object],
        freeSockets: {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        maxCachedSessions: 100,
        _sessionCache: [Object] },
     socketPath: undefined,
     method: 'GET',
     path: '/cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
     parser: null,
     res: [Circular] },
  request:
   Request {
     domain: null,
     _events:
      { error: [Function: bound ],
        complete: [Function: bound ],
        pipe: [Function],
        data: [Function],
        end: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     callback: [Function],
     readable: true,
     writable: true,
     _qs:
      Querystring {
        request: [Circular],
        lib: [Object],
        useQuerystring: undefined,
        parseOptions: {},
        stringifyOptions: {} },
     _auth:
      Auth {
        request: [Circular],
        hasAuth: false,
        sentAuth: false,
        bearerToken: null,
        user: null,
        pass: null },
     _oauth: OAuth { request: [Circular], params: null },
     _multipart:
      Multipart {
        request: [Circular],
        boundary: '70a71426-724f-4b62-9296-5e245402b49a',
        chunked: false,
        body: null },
     _redirect:
      Redirect {
        request: [Circular],
        followRedirect: true,
        followRedirects: true,
        followAllRedirects: false,
        allowRedirect: [Function],
        maxRedirects: 10,
        redirects: [],
        redirectsFollowed: 0,
        removeRefererHeader: false },
     _tunnel:
      Tunnel {
        request: [Circular],
        proxyHeaderWhiteList: [Object],
        proxyHeaderExclusiveList: [] },
     headers: { accept: 'application/json' },
     setHeader: [Function],
     hasHeader: [Function],
     getHeader: [Function],
     removeHeader: [Function],
     method: 'GET',
     localAddress: undefined,
     pool: {},
     dests: [],
     __isRequestRequest: true,
     _callback: [Function],
     uri:
      Url {
        protocol: 'https:',
        slashes: true,
        auth: null,
        host: 'api.weixin.qq.com',
        port: 443,
        hostname: 'api.weixin.qq.com',
        hash: null,
        search: '?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
        query: 'grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
        pathname: '/cgi-bin/token',
        path: '/cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
        href: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37' },
     proxy: null,
     tunnel: true,
     setHost: true,
     originalCookieHeader: undefined,
     _disableCookies: true,
     _jar: undefined,
     port: 443,
     host: 'api.weixin.qq.com',
     path: '/cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
     _json: true,
     httpModule:
      { Server: [Object],
        createServer: [Function],
        globalAgent: [Object],
        Agent: [Object],
        request: [Function],
        get: [Function] },
     agentClass: { [Function: Agent] super_: [Object] },
     agent:
      Agent {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        defaultPort: 443,
        protocol: 'https:',
        options: [Object],
        requests: {},
        sockets: [Object],
        freeSockets: {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        maxCachedSessions: 100,
        _sessionCache: [Object] },
     _started: true,
     href: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
     req:
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 4,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Object],
        connection: [Object],
        _header: 'GET /cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37 HTTP/1.1\r\nhost: api.weixin.qq.com\r\naccept: application/json\r\nC
nnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        method: 'GET',
        path: '/cgi-bin/token?grant_type=client_credential&appid=wxf959acc9ef3df3df&secret=a5eaa93a1f0b75e692c0fb88f8ecdd37',
        parser: null,
        res: [Circular] },
     ntick: true,
     response: [Circular],
     originalHost: 'api.weixin.qq.com',
     originalHostHeaderName: 'host',
     responseContent: [Circular],
     _destdata: true,
     _ended: true,
     _callbackCalled: true },
  toJSON: [Function: responseToJSON],
  caseless:
   Caseless {
     dict:
      { connection: 'close',
        'content-type': 'application/json; encoding=utf-8',
        date: 'Thu, 20 Oct 2016 09:40:53 GMT',
        'content-length': '175' } },
  read: [Function],
  body:
   { access_token: 'FiHj9Q3p1rGFux1oSSiISxR-xNJfCXyFJEUT6NjlXyjhFrgBCoUZ7Ty1SXR_rbwjvBfyPo0m1CzU6QV6Ipaw1FgCKXRczjtXgEDg1BYmboxWE7GLeohv-rsYLT8OEa53XYSaAFASTN',
     expires_in: 7200 } }
Unhandled rejection TypeError: Cannot read property 'expires_in' of undefined
    at E:\慕课网\7天搞定Node.js微信公众号开发\wechat\wechat\g.js:59:32
    at tryCatcher (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\bluebird\js\release\promise.js:510:31)
    at Promise._settlePromise (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\bluebird\js\release\promise.js:567:18)
    at Promise._settlePromise0 (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\bluebird\js\release\promise.js:612:10)
    at Promise._settlePromises (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\bluebird\js\release\promise.js:691:18)
    at Promise._fulfill (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\bluebird\js\release\promise.js:636:18)
    at Request._callback (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\bluebird\js\release\nodeback.js:42:21)
    at Request.self.callback (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\request\request.js:187:22)
    at emitTwo (events.js:87:13)
    at Request.emit (events.js:172:7)
    at Request.<anonymous> (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\request\request.js:1048:10)
    at emitOne (events.js:77:13)
    at Request.emit (events.js:169:7)
    at IncomingMessage.<anonymous> (E:\慕课网\7天搞定Node.js微信公众号开发\wechat\node_modules\request\request.js:969:12)
    at emitNone (events.js:72:20)
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(3)
迷茫

一个 request 请求结果处理有问题

g.js 的 第 55 行的request 改成

request({url: url, json: true}, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        var data = JSON.parse(body);
        var now = (new Date().getTime());
        var expires_in = now + (data.expires_in - 20) * 1000;
        data.expires_in = expires_in;
        resolve(data);
        console.log(data);
    } else {
        reject()
    }
});
伊谢尔伦

雷雷

Ty80

你先看看 response返回是啥再说

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板