简体   繁体   中英

Writing express JS API with node.JS app error

I'm trying to create a REST API in Express.js but I have some issues, I hope that somebody can help me )

my Express.js code:

  router.get( '/apps/download/:downloadId', function ( req, res, next ) {
    const opts = Object.assign( {downloadId: req.params.downloadId}, req.query );
      gplay.download( opts )
      .then( res.json(res) )
      .catch( next );
  });

My Node.js app jQuery code is:

const data = $( '.row' ).eq( 6 ).find( 'table tr' ).map( function() {
    const a = $( this ).find( 'td:first-child a' );
    const td = $( this ).find( 'td:last-child' );

    return {
        version: a.text(),
        href: a.attr( 'href' ),
        date: td.text()
    }
}).get();

console.log( data )

const sdata = $( '.row' ).eq( 7 ).find( 'table tr' ).map( function() {
    const a = $( this ).find( 'td:first-child a' );
    const td = $( this ).find( 'td:last-child' );

    return {
        version: a.text(),
        href: a.attr( 'href' ),
        date: td.text()
    }
}).get();

console.log( sdata )

So when I open '/apps/download/:downloadId' in the browser it gives me only console.log:

[
]

[
    {
         version: '1.0.2',
         href: '/download-app/com.playgendary.kickthebuddy/5_com.playgendary.kickthebuddy_2018-06-09.apk/',
         date: 'June 9, 2018'
    },

    {
         version: '1.0.1',
         href: '/download-app/com.playgendary.kickthebuddy/4_com.playgendary.kickthebuddy_2018-05-28.apk/',
         date: 'May 28, 2018'
    },

    {
         version: 'Varies with device',
         href: '/download-app/com.playgendary.kickthebuddy/5_com.playgendary.kickthebuddy_2018-05-22.apk/',
         date: 'May 22, 2018'
    }
]

However, in the tab browser I get this error: "message": "Converting circular structure to JSON" , but if I change .then(res.json(res)) to .then(res.json.bind(res)) , it gives me nothing, just a clear page.

So I need to get all of this data in REST API on the page in JSON, so what should I do?

You are calling res.json with the res passed into the callback, rather than the result of the promise.

router.get('/apps/download/:downloadId', function (req, res, next) {
    const opts = Object.assign({downloadId: req.params.downloadId}, req.query);
      gplay.download(opts)
      .then(downloadResult => res.json(downloadResult))
      .catch(next);
  });

or

router.get('/apps/download/:downloadId', function (req, res, next) {
    const opts = Object.assign({downloadId: req.params.downloadId}, req.query);
      gplay.download(opts)
      .then(res.json)
      .catch(next);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM