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!
I resolved this issue by having node.js also serve up my static html:
app.use(express.static('public_html'))
I changed to a get request:
$.ajax({
method: "GET",
url: "/list"
})
.done(function( data ) {
console.log(data)
playlist = data
len = playlist.recordings.length
$audio[0].addEventListener('ended',onAudioEnded);
playAudio()
});
and
app.get('/list', (request, response) => {
With this folder structure:
/
app.js
public_html/
index.html
and made sure to access my site from:
http://[mysite].com:3000
Try to do post request like this
$.ajax({
url: "/list",
data:{'auth':'465dsfsd5f44654'},
type: "POST",
headers: {
'Content-Type': 'application/json'
},
success: function (data) {
}
});