Local path referencing when using jQuery.getJSON() method in javascript [duplicate] - javascript

I'm running a local copy of nodejs and have taken some code which runs a web service and references a local index.html on startup. This service is running locally on my desktop.
I've been playing about with CSS, and have found no matter what I do, the style sheet does not load, taking the configuration from the style sheet and dropping this within some <style> elements works fine. But for some reason or another, it's not reading the stylesheet.
Location of style sheet is: c:\program files\nodejs\default.css
HTML code:
<link rel="stylesheet" type="text/css" href="default.css" />
This is in the same location as index.js, index.html. Has permissions etc to read file.
Any ideas why this potentially may not be loading.
index.js code:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res){
fs.readFile('index.html', function (err, data){
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length' : data.length
});
res.write(data);
res.end();
});
}).listen(1337, '127.0.0.1');

Your server:
http.createServer(function (req, res){
fs.readFile('index.html'
… is configured to ignore everything in the request and always return the contents of index.html.
So when the browser requests the stylesheet it is given index.html.
You need to pay attention to the path (which will be in the request) and serve up appropriate content (which for serving up static files means mapping it onto the file system, determining if the file exists or not, then loading that file or a 404 message), with the appropriate content type (so you'd need to determine that for each kind of file), and status code.
This is a significant chunk of work and not worth reinventing the wheel over so it would probably be best done by finding a static file serving module (Google turns up node-static) for Node (or replacing Node with something like Lighttpd or Apache HTTPD).
If you want to serve up dynamic content as well as static content, then Express is a popular choice (and has support for static files).

Related

how to make a node js run a js file and issues creating a js file in node.js console window with win10

I am a beginner in node js and have a couple of months experience with javascript, have finished codecademy js and jquery introductory courses and learned more about js in the internet and have an understanding of html and css in intermediate level or near to intermediate level. I am a complete noob in getting the js and node js to run alltogether. Using VS code for text editor. Node.js is installed from their original homepage, using node.js APP. File named global js.is sticked to 2 folders: the same with node.js and desktop folder for vs code files( the ones I create in VS code as projects or just simple files). The darn thing just doesn't make sense to me and I dont get this mess to work either. To be more specific, then:
I have 2 issues:
Firstly, did an install: npm install javascript bla bla. It was a sucsess, mkdir and cd were successful. NUL >introduction.js says access denied.
Alos I have a file named global.js. It is sitting in the same foler as node.js + the original version of this fie is in the same folder of desktop vs code's excercises. I can't make my node.js open this global.js file.
How do I overcome of these issues?
I tried to use this as a guide line: How to run a hello.js file in Node.js on windows?.
Did following parts of that above: changed account type to ADMINISTRATOR via appwize smth from run. Called cmd from run after having given myself and admin status permanently and windows logged me off and back on again. Tried to run the file from command prompt, declaring the exact path to file in cmd. It reached to the path, showed no error, went to the file from there. No errors, NOTHING didn't happen... Tried the global install whatever faced an issue in there and got stuck with it.
I need some help in here! Would be nice if someone could explain to me what is wrong and what's the basic concept of using node.js or what are the alternative ways to programmetely launch it?
Do I need to use the node.js console or node.js app?
CODE IN main. js :
var http = require("http");
var path= require ("path");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
console.log (`Rock on World from ${path.basename(__filename)}`);
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
No need to use any special console, on windows, standard cmd is enough.
Check if node is installed properly first. Run node -v and see if it prints its version.
Create a folder for your project and make sure your are in it before executing node or npm. Node.exe doesn't have to be in the project folder as long as it is in the path (by default it is)
Make sure your source files in that project folder. (test.js, introduction.js .. whatever you will run)

Why we need http module installed to run our node js application?

I have found so many sources for now when the first application shows this line
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}).listen(8080);
Just being geek, my Question is why we need server/port to listen our requests for our node js applications?
Why can't we run as localhost/application_name instead?
Why we need that?
Can anyone elobarate please?
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
So if you want an application which only work with bash you don't need any http modules.
Browsers use HTTP. So if you want to develop a web application you need to use that protocol. If you run your project on 80 port you can use it like localhost/my_application.
Simple app.js
var result = doSomething();
functions doSomething(){
return "This the result";
}
console.log(result);
You can call it from bash. node app.js. But it just work and stop.
But if you want to serve this structure to WWW (which is using HTTP) you need to create server. http is a great and simple module for creating servers with node.js.
You can use other js files with using require.
app.js
var result = doSomething();
functions doSomething(){
return "This the result";
}
module.exports = result;
server.js
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var result = require('app.js');
res.end(result);
}).listen(80);
Now you can run your server. node server.js
You can run arbitrary javascript with node. The code you've provided specifically sets up an http server that listens on port 8080. You can reach that webserver from a browser on the same computer by browsing to http://localhost:8080.
We don't need to install 'http' module in order to use it, it is already there in nodejs framework itself.
If you want to see output of any programming language you serve it as http because you want your browser to reach your server. Like what you do it php built in server php -S localhost:8081 or serve it via nginx or apache
If you don't serve your JS, PHP, Python ... over http, browser will treat those files as other unsupported file like a .tar file.
Node is JavaScript environment, Not a web server. You need a server to serve your application. You may use http, https or you can create any other server that can serve your js file.
Well, I do not know if my answer is clear enough to explain but hope you will have some idea why you use http module in your nodejs application.

Setting up static assets paths, routing endpoints with koa and various middleares

Question:
How can I set up my static files so that both directories are visible to my index.html.
How can I send my index.html when you hit the default route using koa-router vs. just a .json file when I make an AJAX Get request?
Requirements:
I need static directories to be visible in my apps src/index.html
node_modules needs to be open for js libs.
src/assets needs to be open for images.
I need a router for 2 purposes :
1) serving up the initial index.html
2) CRUD endpoints to my DB.
Notes: I'm totally willing to add/subtract any middleware. But I would rather not change how I organize my directories.
Directory Structure:
Middleware:
koa-static // cant serve node_modules + src directory.
koa-send // can send static files but then breaks koa-static
koa-router // cannot
app.js
var serve = require('koa-static');
var send = require('koa-send');
var router = require('koa-router')();
var koa = require('koa');
var app = koa();
// need this for client side packages.
app.use(serve('./node_modules/'));
// need this for client side images, video, audio etc.
app.use(serve('./src/assets/'));
// Will serve up the inital html until html5 routing takes over.
router.get('/', function *(next) {
// send up src/index.html
});
// will serve json open a socket
router.get('/people', function *(next) {
// send the people.json file
});
app.use(router.routes()).use(router.allowedMethods());
// errors
app.on('error', function(err, ctx){
log.error('server error', err, ctx);
});
app.listen(3000);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Morningharwood</title>
</head>
<body>
<h1>suchwow</h1>
<img src="./assets/image1.png" alt="butts"> <!-- will 404 with routing -->
<script src="./node_modules/gun/gun.js"></script> <!-- will always 404 -->
<script>
var gun = Gun(options);
console.log(gun);
</script>
</body>
</html>
Well. it happens that I'm developing a similar kind of app
There's no problem on using koa-static to serve you static content and koa-router for you api endpoint. I never used koa-send directly. but I think you doesn't need too, given your set up
The only thing that matters is the order when attaching middleware to koa app. Try to attach koa-static first for your assets ( and maybe even index.html) and later use the koa-router for your api. Requests trying to get some static file never reach the router. and this way the router only responsibility will be serving your api
If that's not posible ( for example, because you have a bunch of non-static html files to server, consider taht you can have more than one router per app, even nesting one inside the other
( If the answer is not enough, give some time to cook a simple example. I'll post it as soon as possible)
EDIT: added a quick and dirty example here. Probably it doesn't work out of the box, but it's enough to get the idea

Node.js public static folder to serve js with utf-8 charset

I´m using node.js and express to serve static JavaScript files to a single page application.
In the node.js server code I use express.static to allow public access folder
app.use(express.static(__dirname + '/public/'));
In the client side, I use $.getScript to get the JavaScript files stored in the public folder, for example:
$.getScript("js/init.js");
When I try to get some JavaScript files that have letters with accents or some UTF-8 special character I get strange characters instead of what I want.
Is there any way to set the charset when I define the public folder?
An answer from What's the simplest way to serve static files using node.js? gave me the hint of inserting your own middleware before static.
The code below finds *.js files and sets the charset to utf-8.
app.use(function(req, res, next) {
if (/.*\.js/.test(req.path)) {
res.charset = "utf-8";
}
next();
});
app.use(express.static(__dirname + '/public/'));
After doing this, look for the following response header.
Content-Type: application/javascript; charset=utf-8
In your html pages there has to be the same encoding as the encoding of your resource files (or the other way around)
Make sure you set a meta tag in the head section:
<meta charset='utf-8'></meta>

Requesting a file with node.js server

This is the root of the app (http://site.com), that runs when requesting the domain. If I wanted to add only one file say robots.txt (http://site.com/robots.txt) to be requested using this http server, how would I do that? It would pull from the contents of robots.txt and echo it out.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('homepage');
res.end('');
}).listen(process.env.VMC_APP_PORT || 1337, null);
Thanks
Instead of implementing such a functionality manually, you can build your application with http://expressjs.com/ framework and use static middleware documented at http://expressjs.com/guide.html to server static files. But I would personally prefer to put Nginx in front of Node to serve static file, because it has proven to be efficient for this job and it is all about configuration rather than programming then. Configuration can be different depending on the specific purpose and environment, but mine is documented at http://skovalyov.blogspot.com/2012/07/deploy-multiple-node-applications-on.html

Categories

Resources