Nodejs to provide 1 api endpoint e one html page - node.js

here is my issue.
I never wrote something in node without using express so i find it difficult to create a server with basic APIs.
Basically what I found on the internet is this:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
however I don't see How I can implement /index.html and /getData. This code will run on a Raspberry pie, this is why I shouldnt use libraries. Basically I have no much space.
Many thanks,
h

You'll need to manually inspect the URL in the request and handle each case separate:
var http = require('http');
http.createServer(function (req, res) {
if(req.url == "/index.html") {
fs.readFile("index.html", function(err, text){
res.setHeader("Content-Type", "text/html");
res.end(text);
});
return;
}
if(req.url == "/getData") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('get data\n');
return;
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Just because the code is running on a Pi doesn't mean you can't use modules. Modules don't necessarily take up inordinate space. You'd still have to write the same code many modules have written for you. Modules like Express exist specifically to address the implementation issues you're facing, so you would have to rewrite a router to handle the request for /getData or a file reader for static assets like HTML. Whether you use a module or not, you're going to end up with approximately the same amount of code.
Rather than recreating the wheel, perhaps you just need slimmer modules stripped of the features you don't need. Connect, which Express is based on, is fairly minimal. With either Express or Connect, you can strip out what you don't need. Remember that modules are just a node_modules subdirectory in your project root, so you can remove extraneous things like the tests, examples, and (in several cases) the features you don't need.
Alternatively, there are many slimmer modules like send, which is purely for serving static content like your index page. Journey, which provides JSON-only, is a lean feature set too. The point is there are tons of modules that serve specific needs if Express is too large. The node modules list is a good starting point for finding such modules. Working with node without using modules is kind of like taking a step back to the early days of node when these issues plagued everyone. Of course you can do that, but it has already been done.

Related

How to "run" an HTML webpage without Express, etc

My question can be pretty similar to others, but I already read a lot of answers, but I don't understand completely the details behind them.
I have to create a node.js REST API, but I don't took any lessons before. So i'm currently reading and trying tutorials to learn to create a simple node.js script.
I installed node.js, i created my script (it's just reading an input field), and when i click on a button, it's supposed to write the input in the console.
The tutorial needs only node.js, and use the .createserver. I understand that node.js is server side and can't be interpreted without it.
The tutorial asks to open the .html file in the browser, directly with the path. The html webpage shows up, but... When i'm pressing "ok", here's the errors :
*app.js:1 Uncaught ReferenceError: require is not defined
Access to XMLHttpRequest at 'file:///.../ApplicationAngular/nodeProject/app.html?name=' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
GET file:///.../ApplicationAngular/nodeProject/app.html?name= net::ERR_FAILED*
All the threads on StackOverflow explains that I need a third-party to run the HTML webpage. But on the tutorial, everything is working fine and never mentions the existance of Express, Cheerio, etc..
Here's the samples of code:
app.html
<input type="text" placeholder="Enter your name" id="name"/>
<input type="button" value="OK" onclick="valid()"/>
<div id="message"></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="app.js"></script>
<script>
function valid() {
$.get('', { name: $('#name').val() }, function(data) {
$('#message').html(data.message);
}, 'json');
}
</script>
app.js
var http = require('http');
var url = require('url');
var fs = require('fs');
var server = http.createServer(function (req, res) {
var url_parts = url.parse(req.url, true);
var name = url_parts.query.name;
if(name){
console.log('Nom: ' + name);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(JSON.stringify({message: 'Hello' + name + ' !'}));
} else {
console.log('No name !');
res.writeHead(200, {'Content-Type': 'text/plain'});
fs.readFile('app.html', function (err,data)
{
res.end(data);
});
}
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Is the tutorial missing something? Do I have to install Express in order to view the page web?
Sorry again, english is not my native langage.
Thanks a lot for your answers.
With this line in your html
<script src="app.js"></script> <!-- wrong! -->
you try to run your nodejs program in your browser's javascript interpreter. You need to run it on your server instead. Your browser gacks on the require() operations because those are made to work in nodejs on your server.
Try removing the line from your html, and try doing something like this on your server's command line, then visiting http://localhost:1337 from your browser.
node app.js
The fact that browsers and nodejs support the same language is a bit confusing as you figure this all out. The language is the same but the two runtime environments are quite different. Be patient. You'll get it.
The app.js nodejs program you showed us should function correctly. In its if (name) branch it handles the request coming from the $.get() operation in the browser. In its else branch it delivers the html file to the browser.
And, it has to be said, doing more than just this kind of tutorial with nodejs alone -- without express or some other webserver framework -- gets to be a huge pain in the xxx neck, enough of a pain in the neck that you'll be tempted to develop your own framework.
Edit You have this line twice
res.writeHead(200, {'Content-Type': 'text/plain'}); /* wrong! */
Change both occurrences to
res.writeHead(200, {'Content-Type': 'text/html'});
The Content-Type: text/html header tells your browser to interpret your html file as html, not raw text.

Run multiple node apps on same server and domain

I am wanting to split up an application I have into multiple different applications. I want to start with the presentation layer and the logical layer. I want the HTML, CSS and JS all in it's own application but then have the backend code (API) run in it's own application. I don't understand is how to run both on the same server. Currently my overgrown application runs on port 8080 and I use Nginx to do proxy_pass to port 8080 for the / location.
What do I do here?
Maybe you can run multiple instances of node,of course thats need to be a diferent version. Run in diferent ports and match with proxy_pass.
I Might help you.
My suggestion would be to use view engines, such as EJS etc.
In node.js you can send HTML files to the user, so for example when some one visits www.domain.com/register you send him an HTML file, by using something like this:
var path = require('path'); // Core Module in Node JS
res.sendFile( path.join( __dirname, "register.html" ) ); // Send the register HTML file
Although it wouldn't be the cleanest solution, you could also create multiple servers in the code, each using a different port.
Since you want a Front End and a Back End on the same server, you could make one server for the front end on port 80 ( and 443 if you are using SSL ) and another server on a different port, such as 3000, or whatever your heart desires.
You can then get info from the server with Ajax, or something similar, that is entirely up to you.
Here is an example:
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Front End!');
res.end();
}).listen(80);
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Back End!');
res.end();
}).listen(3000);
I would personally always go with the first example, as it is what most people opt for, and it is much easier to implement.
Also, view engines allow you to embed variables from your node.js application into the HTML files, so there won't be any need for Ajax etc.

Simple web page will not run on xbox one edge browser

I am starting to learn html, css, and nodejs, and after writing a couple of very basic web pages I tried to run them on my computer, and view the page on my xbox-one with edge, but for each one (no matter how simple) it always says "Application is not supported, The webpage tried to start an application, such as an email program, that is not supported on xbox". I've tried with using the node html library as well as the express library, with and without html/css.
One code that would not work on the xbox:
server.js
var http = require('http');
var server = http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("hello world!");
})
var PORT = 1021;
server.listen(PORT);
console.log("Server is running on 192.168.0.15:", PORT, '\n');
I can't find anything online, so any help would be greatly appreciated
Well after a lot of trial and error I found out that it was a very simple problem, I was putting 192.168.0.15:12345 into the address bar but it wanted http://192.168.0.15:1021.

nodejs - dependencies (very basic one) - express - > it is a part of nodejs or a plugin

i am very much interested to learn node.js and now.js . While trying to learn node.js , i found this one http://expressjs.com . Is this a part of node.js that i should learn or it is something like a plugin ?
We can create server simply using this :
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Then y some people use that express ? what is the difference ?
Thankyou.
Express is for web development, where Node.js is for anything server-side javascript.
You can look up the Express.js guide which will tell you way more:
http://expressjs.com/guide.html
Express JS is again a sugar layer or utility module for Node JS to routing requests. its not part of node installable as of now.
but apart from that it has few more features like, (as per the website) -
Robust routing Redirection helpers Dynamic view helpers Application
level view options Content negotiation Application mounting Focus on
high performance View rendering and partials support Environment
based configuration Session based flash notifications Built on
Connect Executable for generating applications quickly High test
coverage
http://expressjs.com/

Internal scripts and style-sheets always points to index file (Node.JS)

This is really weird problem. I just installed Node.JS on my system (Fedora).
I have three files in /var/www/mirror/:
server.js
client.js
index.html
File server.js is the one I call via CLI: node server.js.
It, basically, returns index.html.
var
http = require('http'),
io = require('socket.io'),
fs = require('fs');
http.createServer(function(request, response) {
fs.readFile(__dirname + '/index.html', function(error, data) {
if (error) {
result.writeHead(500);
console.log('Error: Could not read index.html.');
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(data);
});
}).listen(1337, '127.0.0.1');
console.log('Server is running.');
All works as expected and no errors are thrown anywhere.
In index.html I have simple HTML5 structure (nothing unnecessary, really!) and <script /> that points to, already mentioned, client.js.
That line of code looks like this (Ctrl + U; from browser):
<script src="client.js"></script>
By moving cursor on client.js, I got actual location: http://127.0.0.1:1337/client.js.
Seems correct, right?
The problem:
By opening that link it opens wanted file, but the content is as server.js should return.
This disallows me from including any internal scripts and style-sheets!
I guess that anything that goes via http://127.0.0.1:1337/ (also http://127.0.0.1:1337/client.js, http://127.0.0.1:1337/a/b/c etc.) is handled via server.js - and server.js returns index.html (see above).
How can I fix it? Thanks in any advice!
Look at the req.url to tell you the url that the user is requesting. From there, you have to have some code decide whether to serve index.html or client.js.
Also, since I'm guessing index.html isn't changing very frequently, you should probably just read it once, and store the buffer in a variable, rather than reading it on every request.
There are some modules that make serving static files a bit easier. Check out filed for a pretty nice standalone static file

Resources