creating proxy url with meteorjs - meteor

I was wondering how I might achieve the following using Ironrouter in meteorjs:
app.route("/api/tts").get(function(req,res){
res.type('audio/mpeg');
var text = req.query.q;
var request = require('request');
var url = "https://translate.google.pl/translate_tts?ie=UTF-8&q=" + text + "&tl=en&total=1&idx=0&client=t&prev=input";
request.get(url).pipe(res);
});

If you have iron:router installed already, then you already can. All you need to do is install request using meteorhacks:npm.
Then you simply write:
Router.route("/api/tts", function () {
// NodeJS request object
var req = this.request;
// NodeJS response object
var res = this.response;
res.type('audio/mpeg');
var text = req.query.q;
var request = Meteor.npmRequire('request');
var url = "https://translate.google.pl/translate_tts?ie=UTF-8&q=" + text + "&tl=en&total=1&idx=0&client=t&prev=input";
request.get(url).pipe(res);
}, { where: 'server' });
Let me know if that works.

You can't use IronRouter, Meteor routing is done on the client
(the answer from #rclai won't work because the request is still being sent from the client..)
This solution using the WebApp module shipped with Meteor to define server routes is exactly what you need.
e.g. something like this:
import { WebApp } from 'meteor/webapp';
WebApp.connectHandlers.use('/api/tts', (req, res, next) => {
var text = res.query.q;
var url = "https://translate.google.pl/translate_tts?ie=UTF-8&q=" + text + "&tl=en&total=1&idx=0&client=t&prev=input";
HTTP.call("GET", url, {}, function(err, response){
if(err){
res.writeHead(500);
res.end('Failed...');
}
else {
res.end(response.content);
}
});
});

Related

Firebase short URLs not redirecting

I created a Google Sheet that uses a Google Script to generate short URLs via Firebase API.
This is the code in the Google Script
function URLShortener(longURL) {
var body = {
"dynamicLinkInfo": {
"domainUriPrefix": "https://go.example.com",
"link" : longURL
},
"suffix": {
"option": "SHORT"
}
};
var key = 'xxxxxxx'
var url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=" + key;
var options = {
'method': 'POST',
"contentType": "application/json",
'payload': JSON.stringify(body),
};
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
var obj = data["shortLink"];
return obj;
Logger.log(obj)
}
The script works and it generates URLs similar to https://go.example.com/Xdka but these link redirect to https://example.com/Xdka instead of the actual URL that is sent, e.g. https://example.com/final_url.
If I try to generate these short links from the Firebase dashboard the same happens.
Did I misunderstand how these short URLs work or am I missing something?

Make HTTPS call within Firebase Function

I am trying to make a call within a firebase function to a locally managed server. I am not super familiar with node as a development environment so I am not sure what is the issue.
const functions = require('firebase-functions');
const https = require('http');
exports.testPost = functions.https.onRequest((req, res) => {
var options = {
host: 'localdevserver.edu',
port: 80,
path: '/my/endpoint'
};
let data = '';
http.get(options, function(resp){
resp.on('data', function(chunk){
//do something with chunk
data += chunk;
resp.on('end', console.log("dones"));
});
}).on("error", function(e){
console.log("Got error: " + e.message);
});
});
When I look in the Firebase Functions Log, it says either timeout or no reject defined.
With HTTP type functions, you need to send a response to the client in order to terminate the function. Otherwise it will time out.
res.send("OK");
Please read the documentation for more details.
You can use SYNC-REQUEST
npm install sync-request
var request = require('sync-request');
var res = request('GET', 'http://google.com');
console.log(res.body.toString('utf-8'));
the function would be something like this:
exports.testPost = functions.https.onRequest((req, res) => {
var request = require('sync-request');
var res = request('GET', 'http://google.com');
var res = res.body.toString('utf-8');
resp.on(res, console.log("dones"));
});

How to access the HTTP request and response objects in METOR application iron router

I am working on the meteor application ,which has iron router in application .I required to access http request and response object in router ,for accessing the request data.
To access the request and response objects, all you need to do is tell Iron Router that this route is a server only route by passing an options object with { where: 'server' } like so:
Router.route('/hello', function () {
var req = this.request;
var res = this.response;
res.end('hello from the server\n');
}, { where: 'server' });
Or if you want to use different functions for different Methods:
Router.route('/hi', { where: 'server' })
.get(function () {
var req = this.request;
var res = this.response;
res.end('hello from the server\n');
})
.post(function () {
var req = this.request;
var res = this.response;
doSomething(req.body)
res.end('done\n');
});
});
See more in the docs: http://iron-meteor.github.io/iron-router/

Webhook for Mailgun POST?

I am trying to store email messages as JSON (as parsed by Mailgun) in a Mongo.Collection through a Mailgun webhook. I set up an iron-router server-side route to handle the request, but this.request.body is empty. I am using Mailgun's "Send A Sample POST" to send the request, and the POST looks fine using e.g. http://requestb.in/. I was hoping that request.body would have the data, as mentioned in How do I access HTTP POST data from meteor?. What am I doing wrong?
Router.map(function () {
this.route('insertMessage', {
where: 'server',
path: '/api/insert/message',
action: function() {
var req = this.request;
var res = this.response;
console.log(req.body);
...
I'm not sure that is the right syntax. Have you tried using Router.route ?
Router.route('insertMessage',
function () {
// NodeJS request object
var request = this.request;
// NodeJS response object
var response = this.response;
console.log("========= request: =============");
console.log(request);
// EDIT: also check out this.params object
console.log("========= this.params: =============");
console.log(this.params);
// EDIT 2: close the response. oops.
return response.end();
},
{
where: 'server',
path: '/api/insert/message'
}
);
I think the issue is that Mailgun sends a multipart POST request, e.g. it sends "fields" as well as "files" (i.e. attachments) and iron-router does not set up a body parser for multipart requests. This issue is discussed here and here on iron-router's Github Issues. I found this comment particularly helpful, and now I can parse Mailgun's sample POST properly.
To get this working, in a new Meteor project, I did
$ meteor add iron:router
$ meteor add meteorhacks:npm
In a root-level packages.json I have
{
"busboy": "0.2.9"
}
which, using the meteorhacks:npm package, makes the "busboy" npm package available for use on the server via Meteor.npmRequire.
Finally, in a server/rest-api.js I have
Router.route('/restful', {where: 'server'})
.post(function () {
var msg = this.request.body;
console.log(msg);
console.log(_.keys(msg));
this.response.end('post request\n');
});
var Busboy = Meteor.npmRequire("Busboy");
Router.onBeforeAction(function (req, res, next) {
if (req.method === "POST") {
var body = {}; // Store body fields and then pass them to request.
var busboy = new Busboy({ headers: req.headers });
busboy.on("field", function(fieldname, value) {
body[fieldname] = value;
});
busboy.on("finish", function () {
// Done parsing form
req.body = body;
next();
});
req.pipe(busboy);
}
});
In this way I can ignore files (i.e., I don't have a busboy.on("file" part) and have a this.request.body available in my routes that has all the POST fields as JSON.

Basic static file server in NodeJS

I'm trying to create a static file server in nodejs more as an exercise to understand node than as a perfect server. I'm well aware of projects like Connect and node-static and fully intend to use those libraries for more production-ready code, but I also like to understand the basics of what I'm working with. With that in mind, I've coded up a small server.js:
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"};
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if(!exists) {
console.log("not exists: " + filename);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
}
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
res.writeHead(200, mimeType);
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
}); //end path.exists
}).listen(1337);
My question is twofold
Is this the "right" way to go about creating and streaming basic html etc in node or is there a better/more elegant/more robust method ?
Is the .pipe() in node basically just doing the following?
.
var fileStream = fs.createReadStream(filename);
fileStream.on('data', function (data) {
res.write(data);
});
fileStream.on('end', function() {
res.end();
});
Thanks everyone!
Less is more
Just go command prompt first on your project and use
$ npm install express
Then write your app.js code like so:
var express = require('express'),
app = express(),
port = process.env.PORT || 4000;
app.use(express.static(__dirname + '/public'));
app.listen(port);
You would then create a "public" folder where you place your files. I tried it the harder way first but you have to worry about mime types which is just having to map stuff which is time consuming and then worry about response types, etc. etc. etc.... no thank you.
Your basic server looks good, except:
There is a return statement missing.
res.write('404 Not Found\n');
res.end();
return; // <- Don't forget to return here !!
And:
res.writeHead(200, mimeType);
should be:
res.writeHead(200, {'Content-Type':mimeType});
Yes pipe() does basically that, it also pauses/resumes the source stream (in case the receiver is slower).
Here is the source code of the pipe() function: https://github.com/joyent/node/blob/master/lib/stream.js
I like understanding what's going on under the hood as well.
I noticed a few things in your code that you probably want to clean up:
It crashes when filename points to a directory, because exists is true and it tries to read a file stream. I used fs.lstatSync to determine directory existence.
It isn't using the HTTP response codes correctly (200, 404, etc)
While MimeType is being determined (from the file extension), it isn't being set correctly in res.writeHead (as stewe pointed out)
To handle special characters, you probably want to unescape the uri
It blindly follows symlinks (could be a security concern)
Given this, some of the apache options (FollowSymLinks, ShowIndexes, etc) start to make more sense. I've update the code for your simple file server as follows:
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"};
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), unescape(uri));
var stats;
try {
stats = fs.lstatSync(filename); // throws if path doesn't exist
} catch (e) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
return;
}
if (stats.isFile()) {
// path exists, is a file
var mimeType = mimeTypes[path.extname(filename).split(".").reverse()[0]];
res.writeHead(200, {'Content-Type': mimeType} );
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
} else if (stats.isDirectory()) {
// path exists, is a directory
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Index of '+uri+'\n');
res.write('TODO, show index?\n');
res.end();
} else {
// Symbolic link, other?
// TODO: follow symlinks? security?
res.writeHead(500, {'Content-Type': 'text/plain'});
res.write('500 Internal server error\n');
res.end();
}
}).listen(1337);
var http = require('http')
var fs = require('fs')
var server = http.createServer(function (req, res) {
res.writeHead(200, { 'content-type': 'text/plain' })
fs.createReadStream(process.argv[3]).pipe(res)
})
server.listen(Number(process.argv[2]))
How about this pattern, which avoids checking separately that the file exists
var fileStream = fs.createReadStream(filename);
fileStream.on('error', function (error) {
response.writeHead(404, { "Content-Type": "text/plain"});
response.end("file not found");
});
fileStream.on('open', function() {
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
response.writeHead(200, {'Content-Type': mimeType});
});
fileStream.on('end', function() {
console.log('sent file ' + filename);
});
fileStream.pipe(response);
I made a httpServer function with extra features for general usage based on #Jeff Ward answer
custtom dir
index.html returns if req === dir
Usage:
httpServer(dir).listen(port);
https://github.com/kenokabe/ConciseStaticHttpServer
Thanks.
the st module makes serving static files easy. Here is an extract of README.md:
var mount = st({ path: __dirname + '/static', url: '/static' })
http.createServer(function(req, res) {
var stHandled = mount(req, res);
if (stHandled)
return
else
res.end('this is not a static file')
}).listen(1338)
#JasonSebring answer pointed me in the right direction, however his code is outdated. Here is how you do it with the newest connect version.
var connect = require('connect'),
serveStatic = require('serve-static'),
serveIndex = require('serve-index');
var app = connect()
.use(serveStatic('public'))
.use(serveIndex('public', {'icons': true, 'view': 'details'}))
.listen(3000);
In connect GitHub Repository there are other middlewares you can use.

Resources