Monday 1 May 2017

how to retrieve data from a node.js file with jquery ajax

I'm new to nodejs and trying to figure out how to get twilio data from a working node script via ajax on the front end.

I have this on the backend

'use strict';

const express = require('express');
const twilio = require('twilio');

const accountSid = '####';
const authToken = "####";
const client = require('twilio')(accountSid, authToken);

const baseURL = 'https://api.twilio.com'
const recordingExtension = '.mp3' //mp3 or wav

let app = express();

app.post('/list', (request, response) => {
  const recordings =[]
  client.recordings.list(function(err, data) {
      data.recordings.forEach(function(recording) {
          var recordingURIComponent = recording.uri.replace('.json','')
          var recordingURL = baseURL + recordingURIComponent + recordingExtension
          recordings.push(recordingURL)
      });
      const recordingData = {
        recordings: recordings
      }
      response.send(recordingData)
  });
});


app.listen(3000, '127.0.0.1',function(){
  console.log('listening');
});

and now I want to access that response from ajax on the front end.

I know it could look something like:

$.post( '/list', function(data) {
  console.log(data)
});

But I'm not sure where to direct my post/get/ajax to. If both files are on the same server, what URL do I use as the post request? Do I need to specify the port (3000?). Or do I need to do something in express to serve up the html file that will do the ajax request?

Any help is appreciated. Thanks!



via mheavers

No comments:

Post a Comment