Node - Tell origin of request - node.js

Is it possible to tell the difference between a request coming directly from a URL in a browser vs. a resource being called from a remote web page?
For example, I would like to serve a web page when someone visits my URL directly (types in http://mywebsite.com) in a web browser, but when a user calls a resource on my app via a url from a seperate domain (like <img src='http://mywebsite.com' />) then I'd like to serve different content.
I've looked in the request and in the headers but it looks the same regardless of

I think you are looking for the referer string in the request.header.
So the simple version would look like this:
http.createServer(function (req, res) {
var ref = req.headers.referer;
if(ref) {
// serve special content
}
else {
// serve regular homepage
}
}).listen(1337, '127.0.0.1');
edited the answer to reflect the input from anu below - it should be referer

In middleware you have to use this way "req.headers.origin"
app.use(function(req, res, next) {
//var origin=req.headers.origin
next();
});

Related

How to add readable text to URL with NodeJS Express?

I have links that looks like this on my website:
https://website.com/view?id=8d23iva
When users go to the link, I want the URL to change based on information related the id parameter like this:
https://website.com/view?id=8d23iva/amazing-book-title
I have been messing around changing the req and res object data before the user is sent to the page similarly to this.
app.get('/view', (req, res, next) => {
res.baseUrl = "/test";
req.url = req.url + '/test';
req.originalUrl = req.originalUrl + '/test';
next();
});
As an HTTP server, the primary way you can influence the client (i.e the users browser) is with your HTTP response. To change their location you can return a redirection response.
A redirection response is any HTTP response with a 3XX status code and a Location header set to the new destination. In express you can use res.redirect(/*your location here*/) to send a redirection response. For more information about different types of redirects check out this MDN article.
As a side note, you could also consider making the change to the location using javascript on the client once the page is loaded. Though this will depend on other factors. You could investigate the History api for this.

can node HTTPS server be created without public and private keys?

I am using expressjs to create an http/https server.
There was a case wherein the server was not able to fetch the public and private certificate files from a directory.
In which case I create the server using http and send a raw HTML file to the client indicating that there was an issue, but here lies the problem,
the user does not know that they need to move to http url rather than https to see the HTML file.
So is there a way I can redirect my users to a https url when they try to access the http URL
init.js
try {
// options = get public and private certificate file
} catch(e) {
// accessError
}
if(accessError) {
server = http.createServer();
} else {
server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
});
);
}
server.listen(8080);
app.js
let app = require('express');
app.use((req, res, next) => {
if(accessError) {
res.sendFile(index.html);
} else {
next();
}
});
index.html
<h1> there was an error <h1>
You can try a 301 Redirect like in the answer to this question.
Whenever somebody tries to access the http variant of a resource, they'll be redirected to the https one.
As a design decision I'd treat the inability to retrieve certificates as a fatal error. I imagine you're reading them at start time. If you can't read them for some reason, you should just terminate the application, and log an exception. You do need to have some monitoring in place to notice that the thing hasn't started and act accordingly when you can't find it. But displaying an error page seems like more trouble than it's worth. You're going to have the application in an up state, but not really. Cause it won't be able to do anything, and you'll need to rely on clients telling you that it doesn't work and there's a https related message etc. Better to fail hard.

How can I redirect facebook crawler bot to another webpage?

I've developed small website done by PreactJS which has some parts of main website (PHP). As we all know, Facebook bot cannot crawl javascript pre-render content while sharing. That's why I want to redirect as letting facebook bot to crawl main website (PHP) while sharing a link of website done by PreactJS in NodeJS/ExpressJS as follow:
if user is sharing like, 'https://www.mywebsite.com/category/trips/10' I want nodejs/express to redirect 'https://main.mywebsite.com/category/trips/10'. Can anyone tell me how can I do like that in expressjs level as follow:
app.use('/*', function(req, res){
if(req.headers['user-agent'] === 'facebookexternalhit/1.1') {
}
});
Instead of redirecting, I strongly recommend proxying that data. Otherwise, Facebook is going to assume that your URL is a redirect for regular users as well.
Consider a module like express-http-proxy, which makes this simple. Untested, but this should get you started:
app.use((req, res, next) => {
if (
!req.headers['user-agent'] ||
!req.headers['user-agent'].startsWith('facebookexternalhit')
) {
return next();
}
return proxy('main.mywebsite.com')(req, res);
});
app.use('/*', function(req, res){
if(req.headers['user-agent'] === 'facebookexternalhit/1.1') {
res.redirect("https://main.mywebsite.com/category/trips/10")
}
});
You can use res.render() if you want to redirect it to a view you have created

Building a proxy server with Express and Request

I need to build a small nodejs app that receives a request as such:
http://localhost?url=http://www.someurl.com
The server needs to receive the request, download the page from given url, modify its HTML, and return it to the client (proxy?)
router.get('/', function(req, res, next) {
// Get url from the query
var url = decodeURIComponent(encodeURIComponent(req.query.url));
request(url, function(error, response, html) {
// ...
// DO SOME MODIFICATIONS TO THE HTML HERE
// ...
res.send(html);
});
});
My current problem is that css/js files that have relative URLs aren't being forwarded to their origin, but instead, they're being sent to download from my server like this:
http://localhost/css/some-css-file.css
http://localhost/js/some-js-file.js
This is just part of the problem, all other resources with relative URLs, and all HTTP requests that page makes that aren't an absolute URL request, are also going to the root host which is localhost in my case.
I've done some research but couldn't quite get the whole deal of how to do this properly.
Is the pipe function what I need ? I don't quite get how to use it.

transmission rpc with expressjs

i currently have transmission-daemon web ui served by nginx
server {
listen 2324;
server_name torrent.example.com;
location /rpc {
proxy_pass http://127.0.0.1:9091/transmission/rpc;
}
location /transmission {
proxy_pass http://127.0.0.1:9091/transmission;
}
location / {
proxy_pass http://127.0.0.1:9091/transmission/web/;
}
}
i am trying to display this page via https://github.com/stormpath/stormpath-express-sample this dashboard/user interface
in routes/index.js i have
router.get('/torrent', function (req, res, next) {
if (!req.user || req.user.status !== 'ENABLED') {
return res.redirect('/login');
}
var newurl = 'http://127.0.0.1:2324'
request(newurl).pipe(res)
});
i see the html when i goto /torrent but no images/css/js i am thinking the request is not the right tool for this purpose could some one offer a better solution
many thanks
Your HTML probably refers to CSS/images/etc using URLs such as /index.css. The browser makes these into fully-qualified URLs that look like http://torrent.example.com/index.css, which is not proxied by ngnix the way you have it set up.
You probably want to either use URLs such as /transmission/index.css for your CSS (when specified in the HTML), or alternatively have a <base> tag in your HTML for that.
ok so i have made progress with html/css i moved the transmission interface into the express root and imported the html into jade but now i am having a new problem
when i load the /torrent page i can seen in the web console it makes a request to /rpc which i have made a route for
router.get('/rpc|/rpc/', function (req, res) {
var newurl = 'http://127.0.0.1:9091/torrent/rpc/'
request(newurl).pipe(res)
});
but this comes up with a 404 when i change router.get to router.post i get a 405 error
i have removed the 409 error from transmission so this should work
i have solved the issue
i imported the transmission index.html into a jade template
i routed /torrent to render that template
then i made a new route for /rpc|/rpc/ made that do a post request to the backend transmission-daemon
i also changed /js/remote.js to look for the RPC._Root at the atchual domain

Resources