Simple Meteor http call timing out - json

I wish to get some currency prices from a web service which provides them in JSON format.
Here is the code I am using with the simple example (hello world) -
if (Meteor.isClient) {
Template.hello.greeting = function () {
return "Welcome to webserve.";
};
Template.hello.events({
'click input' : function () {
// template data, if any, is available in 'this'
if (typeof console !== 'undefined')
console.log("You pressed the button");
Meteor.call('getprice');
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
Meteor.methods({
getprice: function() {
console.log('On the server');
var url = "http://quotes.instaforex.com/get_quotes.php?m=json&q=AUDUSD";
//var url ="http://www.google.com";
HTTP.get(url, function(error, result) {
if(!error) {
console.log(result.content);
}
else console.log(error);
});
}
});
}
When I run the app, and click the button in the client, i get a timeout message on the server.
Notice the url - If I copy/paste it in a browser I receive the right json,
Cross Domain policy does not apply because the code is on server side.
Any ideas?

Copying into a new project helped, no change required.

Related

Uploading TinyMCE local images to different server from one on which TinyMCE is hosted: all 'http' references are lost

I'm uploading local images to a remote server using TinyMCE's images_upload_handler. This works fine, that is, the image is uploaded, but the HTML that TinyMCE returns will not seem to accept any src reference that contains http. I'm integrating TinyMCE as part of KeystoneJS, so perhaps there's something in the connection that's sanitising the HTML, but I'm a bit stumped.
My images_upload_handler is
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
console.warn('!!!!');
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'http://localhost:4545/tinymceimage');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
console.log('json.location',json.location);
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
and my server handler is
app.post('/tinymceimage', function tinyMCEUpload(req, res) {
console.log('files', req.files);
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile: UploadedFile = req.files.file as UploadedFile;
// Use the mv() method to place the file somewhere on your server
console.log(sampleFile.name);
const out = path.resolve(__dirname, '../../static_files', sampleFile.name);
fs.writeFile(out, sampleFile.data, 'base64', function(err) {
if (err) console.log(err);
if (err) res.send(err);
res.json({ location: `http:localhost:4545/${sampleFile.name}` });
});
});
but the HTML returned from TinyMCE does not contain correct image src's, for instance NOT
<img src="http://localhost:4545/blop.jpg" />,
but rather
<img src="../../blop.jpg" />
If I change
res.json({ location: `http:localhost:4545/${sampleFile.name}` });
to
res.json({ location: `something/${sampleFile.name}` });
I get
<img src="something/blop.jpg" />

How do i subscribe live stream video in agora?

I am setting up agora SDK to my angular project and am getting the following error.
Code:
This is my sample code and is calling the startCall method in ngOnInit. I have a div element with id.
startCall() {
this.agoraService.client.join(null, '1000', null, (uid) => {
this.localStream = this.agoraService.createStream(uid, true, null, null, true, false);
this.localStream.setVideoProfile('720p_3');
this.subscribeToStreams();
});
}
private subscribeToStreams() {
this.localStream.on("accessAllowed", () => {
console.log("accessAllowed");
});
// The user has denied access to the camera and mic.
this.localStream.on("accessDenied", () => {
console.log("accessDenied");
});
this.localStream.init(() => {
console.log("getUserMedia successfully");
this.localStream.play('agora_local');
this.agoraService.client.publish(this.localStream, function (err) {
console.log("Publish local stream error: " + err);
});
this.agoraService.client.on('stream-published', function (evt) {
console.log("Publish local stream successfully");
});
}, function (err) {
console.log("getUserMedia failed", err);
});
// Add
this.agoraService.client.on('error', (err) => {
console.log("Got error msg:", err.reason);
if (err.reason === 'DYNAMIC_KEY_TIMEOUT') {
this.agoraService.client.renewChannelKey("", () => {
console.log("Renew channel key successfully");
}, (err) => {
console.log("Renew channel key failed: ", err);
});
}
});
// Add
this.agoraService.client.on('stream-added', (evt) => {
const stream = evt.stream;
this.agoraService.client.subscribe(stream, (err) => {
console.log("Subscribe stream failed", err);
});
});
// Add
this.agoraService.client.on('stream-subscribed', (evt) => {
const stream = evt.stream;
if (!this.remoteCalls.includes(`agora_remote${stream.getId()}`)) this.remoteCalls.push(`agora_remote${stream.getId()}`);
setTimeout(() => stream.play(`agora_remote${stream.getId()}`), 2000);
});
// Add
this.agoraService.client.on('stream-removed', (evt) => {
const stream = evt.stream;
stream.stop();
this.remoteCalls = this.remoteCalls.filter(call => call !== `#agora_remote${stream.getId()}`);
console.log(`Remote stream is removed ${stream.getId()}`);
});
// Add
this.agoraService.client.on('peer-leave', (evt) => {
const stream = evt.stream;
if (stream) {
stream.stop();
this.remoteCalls = this.remoteCalls.filter(call => call === `#agora_remote${stream.getId()}`);
console.log(`${evt.uid} left from this channel`);
}
});
}
I have a div element with id.
Uncaught (in promise) TypeError: Failed to execute 'getStats' on 'RTCPeerConnection': The callback provided as parameter 1 is not a function.
at Object.C.t.getStats (AgoraRTCSDK.min.js:2)
at AgoraRTCSDK.min.js:2
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:498)
at ZoneTask.invoke (zone.js:487)
at timer (zone.js:2281)
Does anyone face the same issue? Can anyone help me with this?
Thanks.
I have followed this link
https://docs.agora.io/en/Interactive%20Broadcast/web_prepare?platform=Web
Steps I have done,enter code here
1. Import the Agora Web SDK to Your Project
2. Create and Initialize a Client
3. Join a Channel
4. And finally, Subscribe to the remote stream
When testing Agora's WebSDK (or any WebRTC application) make sure that you are using an https connection when trying to run your code as most browsers do not allow getMedia access without an https connection.
There are a number of solutions for using https connections on your local machine. I use the ngrok tool to easily run https connections on my local machine

How to map URL to node.js route

I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.
For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?
My AngularJS controller code:
$scope.getResults = function() {
$location.search('color', $scope.myColor);
$location.search('size', $scope.mySize);
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
In Node.js, I have my route like this:
app.get("/results", function (req, res) {
var api = 'some api call/' + req.query.color + '/' + req.query.size;
request(api, function (error, response, api) {
if (!error && response.statusCode == 200) {
res.json({
Response: api
});
}
});
});
In your code you wrote query parameters but you need to read them, try this:
$scope.getResults = function() {
$scope.myColor = $location.search().color;
$scope.mySize = $location.search().size;
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};

Ionic Framework giving error while displaying json data

I am using Ionic Framework and WP-API to develop a mobile app for my Woocommerce based website.I am using the following URL to retriece JSON data about my products from the website -
http://example.com/wp-json/posts?type=product&?_jsonp=JSON_CALLBACK
When I try this URL from my browser, I get a perfect JSON response, with all the required details about my products. However, when i try calling the same URL through Ionic, the framework throughs an error.
UPDATE
$http.jsonp( postsApi ).
success(function(data, status, headers, config) {
$scope.posts = data;
console.log( data );
}).
error(function(data, status, headers, config) {
console.log( 'Post load error.' );
});
Please provide a working link to try it again.
Try using service:
app = angular.module('appName', ['ionic']);
app.factory('postService', function($http){
return {
all: function all() {
var url = 'http://example.com/wp-json/posts?type=product&?_jsonp=JSON_CALLBACK';
return $http.jsonp(url, {cache: true})
.success(function(data){
return data;
}).error(function() {
alert("Error");
});
}
}
});
app.controller("ItemController", function($scope,postService){
$scope.item = [];
postService.all().then(function(data){
data = data.data;
if(data.length == 0){
console.log('empty return');
}else{
$scope.item = data;
}
});
});

Angular Seed project, set index.html by default

I am using the Angular Seed project to build a simple website. When i start the node server and enter the url at localhost:8000, it serves up the directory contents. I would like it to serve up the index.html file but would like to do this without a redirect.
I believe that I need to modify the following function and that I should change the code for the isDirectory check but I'm not sure if that is the correct way to go about doing this. Any suggestions would be appreciated.
StaticServlet.prototype.handleRequest = function(req, res) {
var self = this;
var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
return String.fromCharCode(parseInt(hex, 16));
});
var parts = path.split('/');
if (parts[parts.length-1].charAt(0) === '.')
return self.sendForbidden_(req, res, path);
fs.stat(path, function(err, stat) {
if (err)
return self.sendMissing_(req, res, path);
if (stat.isDirectory())
return self.sendDirectory_(req, res, path);
return self.sendFile_(req, res, path);
});
}
Update #1
I have two screenshots to clarify. The first image is what I currently get, the second image is what I want.
What I Get
What I Want
Update #2
Using the link to Restify below I found the following example which is exactly what I needed.
var server = restify.createServer();
var io = socketio.listen(server);
server.get('/', function indexHTML(req, res, next) {
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
next(err);
return;
}
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end(data);
next();
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
server.listen(8080, function () {
console.log('socket.io server listening at %s', server.url);
});
The angular-seed project is a starting point for the client, but not really for the server side.
They included a simple web-server node script without dependencies. This way you don't need npm or other modules.
For the server side you can use node with connect/express or any other web server/language.
You just need to make rest services and serve some static html.
Since you have already installed Node restify may be something for you.
Update: I created a basic sample for using the angular-seed with restify:
https://github.com/roelandmoors/restify-angular-seed