nodejs couchapp does not link css file - node.js

I have made a couchdb design document which works perfectly on the following url
http://localhost:5984/db/_design/app/index.html
Now the problem is i am trying to fetch the page contents and display it from node js but only the html page is displayed the linked css and js files are not working and when i tried to narrow down the problem i found that the css and js files are suppose to have the login credentials of the couchdb and is not linking I even tried adding the auth header in the response parameter but still no luck
var http = require('http');
var json;
var root = new Buffer("admin:pass").toString('base64');
http.createServer(function(req, res) {
res.setHeader('Authorization', root);
res.writeHead(200, { 'Content-Type':'text/html' });
couchPage();
res.end(json);
}).listen(8080);
function couchPage() {
var options = {
hostname: 'localhost',
port: 5984,
path: '/db/_design/app/index.html',
auth: 'admin:pass',
method: 'GET'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
json = chunk;
});
});
req.end();
}
could any one please guide me where am i wrong

I think this has nothing to do with couchdb authorization. The problem is that you do not perform any routing on your nodejs server. That is, the browser makes a request to localhost:8080 and receives the content of /db/_design/app/index.html as an answer. Now, the browser detects a link to a stylesheet, say "style.css". It performs a request to localhost:8080/style.css but your nodejs server simply ignores the "style.css" part of the request. Instead, the client will receive the content of /db/_design/app/index.html again!
If you want to serve attachments of your design document through nodejs, you have to parse the request first and then retrieve the corresponding document from couchdb. However, I don't think that you actually want to do this. Either you want to use couchdb in a traditional way behind nodejs (not directly accessible from the client) and then you would just use it as a database with your html (or template) files stored on disk. Or you want to directly expose couchdb to the client and make nodejs listen to events via the couchdb _changes feed.

Related

How to create a proxy download in Nodejs

I want to create a nodejs server which is acting a proxy to download files i.e. user clicks
on the a download button, call get from nodejs server, nodejs server fetches link from a different
remote server and starts the download (in terabytes). This download is then forwarded to the user.
The terabyte file should not be stored on the nodejs server and then sent.
Here is my attempt:
function (request, response) {
// anything related to the remote server having the file
var options= {
path: "./bigData",
hostname:"www.hugeFiles.net"
}
// get the file from the remote server hugefiles and push to user's response
https.get(options, function(downFile)) {
downFile.pipe(response)
}
}
Before I was using res.download(file, function(err)) {} but file has to be downloaded completely from the remote server
You're very close, you're sending the right http body but with the wrong http headers.
Here's a minimal working example:
const express = require('express');
const http = require('http');
const app1 = express();
app1.get('/', function (req, res) {
res.download('server.js');
});
app1.listen(8000);
const app2 = express();
app2.get('/', function (req, res) {
http.get({ path: '/', hostname: 'localhost', port: 8000}, function (resp) {
res.setHeader('content-disposition', resp.headers['content-disposition']);
res.setHeader('Content-type', resp.headers['content-type']);
resp.pipe(res);
});
});
app2.listen(9000);
Though I would say you should take a look at modules like https://github.com/nodejitsu/node-http-proxy which take care of the header etc . . . for you.
There is no way for your server to provide a file to the client without the server downloading it first.
What you may want to do instead is provide the client with a download link to the huge file. To make it seem automatic, you can create html which starts a download from the content provider automatically and serve that to the client.
In other words, in the scenario you are describing, the server is acting as a middleman between your client and the content provider. Unless the server needs to process the data or the client isn't allowed to retrieve the data themselves, it makes more sense to cut out the middleman.

http.request vs http.createServer

What is the difference between the request in this line of code:
http.createServer(function(request,response){. . .}
and request in
http.request()
Are both requests done to the server?
I am new to node.js and I am sorry if I sound dumb!
How does http.request() work?
In http.request() we fetch data from another site but in order to fetch data from another site we first need to go to our site and then make a request? Explain it with a simple real-life example!
http.request() makes a request to another HTTP server. Suppose for some reason I wanted to go download Stack Overflow's home page...
http.request('https://stackoverflow.com/', (res) => {
// ...
});
http.createServer()... it creates an HTTP server. That is, it binds your application to a socket to listen on. When a new connection is made from somewhere or something else, it handles the underlying HTTP protocol of that request and asks your application to deal with it by way of a callback. From the Node.js documentation:
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
These two methods have absolutely nothing to do with each other. http.request() is for making a request to an HTTP server. http.createServer() is for creating your own HTTP server. Don't get confused by the callbacks.
Based on the source code of nodejs (extract below), createServer is just a helper method to instantiate a Server.
Extract from line 1674 of http.js.
exports.Server = Server;
exports.createServer = function(requestListener) {
return new Server(requestListener);
};
The http.request() API is for when you want your server code to act as a client and request content from another site and has GET, POST, PUT, DELETE methods.

Google Maps Javascript API on Node.JS

I'm working on a NodeJS project that requires me to obtain driving directions on the server.
It seems like an obvious choice to use the Google Javascript API Version 3. But it seems like it was made only to be used on HTML pages, and not on server-only scripts. Even loading the API requires a script-tag or document.write.
Then I turned to node-googlemaps which is based on the Google Maps API. Sadly, this also does not work for two reasons:
the returned travel steps do not contain the path field
the license does not allow to use that API without displaying a map to a user
What can I do? Are there any workarounds or other APIs I could use?
Best, Boris
Actually you can do it on the backend or frontend, and the approach is basically the same.
All you gotta do is a request to the endpoint passing the right parameters, then the API will return you everything you need.
So, roughly it would be something like this:
var http = require('http');
var options = {
host: 'maps.googleapis.com',
path: '/maps/api/directions/json?origin=Toronto&destination=Montreal&avoid=highways&mode=bicycling'
}
callback = function(response) {
// variable that will save the result
var result = '';
// every time you have a new piece of the result
response.on('data', function(chunk) {
result += chunk;
});
// when you get everything back
response.on('end', function() {
res.send(result);
});
}
http.request(options, callback).end();
And here's the documentation's link if you want to dig deeper on this: https://developers.google.com/maps/documentation/directions/?hl=nl
Cheers,

Easiest way to persist/cache a web response

I'm playing with node.js. Using http-proxy, I want to create a simple web proxy that makes the request and then stash the response somewhere before passing back the response. If I then detect no internet connection or some flag is set somewhere, I want to replay the response that I have stashed away. So the URL would be the "key" and the entire response would be the "value".
My question is, what's the easiest way to serialize this response object so that it can be replayed later? I was looking at mongodb and mongoosejs, but I'm put off because mongoose wants me to create a schema for my object, and I just want to dump the entire response object somewhere (with the URL as a key). Is there an easier way?
Here's my super simple node.js proxy code:
var httpProxy = require('http-proxy');
var server = httpProxy.createServer(function (req, res, proxy) {
var buffer = httpProxy.buffer(req);
proxy.proxyRequest(req, res, {
host: 'url.to.proxy.com',
port: 80,
buffer: buffer
});
});
server.proxy.on('end', function (req) {
console.log("The request was proxied.",req.url);
});
server.listen(8000);
The easiest way is to store the response object in a file; you don't need a database.
Create a response object cache directory.
Hash the URL using SHA-256 and use the result as your file name.
Stream the response object to/from the file.

nodejs configuration httpd.conf

I'm used to apache and putting configuration items in httpd.conf
Where do these types of configurations go in a node environment. For example, I want to make sure that only GET, POST, and PUT are accepted and Head and Trace are not accepted. Where does a config like that go?
Additional things like Cache-Control and limiting request and response sizes.
Node.js is just a JS framework with a system API. Technically, you could reimplement Apache HTTP Server in Node.js, mimicking its behaviour and its configuration structure. But would you?
I believe you are using Node.js' HTTP module. Look at the docs: there's no way to read configuration from a file. The server is programmatically created using http.createServer. You provide a callback that listens to requests. This callback provides an http.IncomingMessage parameter (first parameter) which contains everything you need.
Here's an example:
// load the module
var http = require('http');
// create the HTTP server
var server = http.createServer(function(request, response) {
// use the "request" object to know everything about the request
console.log('got request!');
// method ('GET', 'POST', 'PUT, etc.):
console.log('HTTP method: ' + request.method);
// URL:
console.log('HTTP URL: ' + request.url);
// headers:
console.log('HTTP headers follow:');
console.log(request.headers);
// client address:
console.log('client address: ' + request.socket.address().address);
});
// listen on port 8000
server.listen(8000);
If you really want a configuration file, you will have to forge it yourself. I suggest creating a JSON configuration file as this can be turned directly into a JS object using JSON.parse(). Then just use your configuration object programmatically to achieve what you want.

Resources