I would like to know why is there a difference when I launch my project with NodeJS and when I launch directly with the HTML file.
Here is what I am supposed to have (with the HTML file) :
And here is what I have through NodeJS :
As you can see, it seems that the VueJS variable is not working anymore.
I don't know why because, i just create a short NodeJS program to launch this HTML file. I know that it is not a huge problem and can be easily solved.
Here is my JS program
var http = require ('http');
var fs = require('fs');
var port = 3000
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type': 'text/html'})
fs.readFile('index.html', function(error,data){
if (error) {
res.writeHead(404);
res.write('Error file not found');
}else {
res.write(data);
}
res.end();
})
})
server.listen(port,function(error){
if(error){
console.log('Something went wrong', error);
}else {
console.log("server is listening on port 3000");
}
})
Thank you guys in advance for your help. I look forward to see your responses.
Related
So I'm creating a game with HTML, css, and javascript, and I'm trying to incorporate template engines/ajax in this task. I made a server which if I run in cmd and then open up google chrome and type 'localhost:3000' in the address line, it is supposed to direct me to the main.html page.
However, when I type 'node server.js' in cmd, it runs properly but when I enter 'localhost:3000' in the browser it says the page does not exist. I'm not sure what went wrong. If I were to manually double click on the html file in my folder, it works, but I'm trying to get it to load by running a server.
I have three folders (img, node_modules, and pages) and 2 json packages which were created by installing express and pug. It's hard to explain my folder paths and code here, so I have a link to a folder containing my files/sub folders and it also gives a clearer view of the path in my directory: https://github.com/jessaisreal/game
It wouldn't let me upload the node_modules folder as it was too big, but I automatically got it from typing 'npm init', 'npm install express' and 'npm install pug' into the cmd line in the folder.
I'm assuming something is wrong with my server.js file or the way my folders are set up. I'm really desperate to get my program working and would appreciate any help. I have no idea why my html page isn't loading. I'm also not sure if I handled the GET request for getting specific fonts correctly.
I cut down my program as much as I could. There are several html and css files, but only included create and main here for simplicity. Again, I would appreciate any help or a push in the right direction!!
server.js:
const http = require('http');
const fs = require("fs");
const pug = require("pug");
//user pug functrion to render through the create Page
const renderMain = pug.compileFile('pages/main.pug');
const renderCreate = pug.compileFile('pages/create.pug');
//Helper function to send a 404 error
function send404(response){
response.statusCode = 404;
response.write("Unknown resource.");
response.end();
}
// Helper function to send 500 server error;
function send500(response){
response.statusCode = 500;
response.write("Server error.");
response.end();
}
// initilize the server
const server = http.createServer(function (request, response) {
//console.log(request.method+" -> "+request.url); test about the income request
// handle the get request
if(request.method === "GET"){
if(request.url === "/" || request.url === "/main"){
let data = renderHome("./pages/main.pug",{})
response.statusCode = 200;
response.end(data);
}else if(request.url === "/main.js"){
//read main.js file and send it back
fs.readFile("main.js", function(err, data){
if(err){
send500(response);
return;
}
response.statusCode = 200;
response.setHeader("Content-Type", "application/javascript");
response.write(data);
response.end();
});
}else if(request.url === "/main.css"){
//read css file
fs.readFile("main.css", function(err, data){
if(err){
send500(response);
return;
}
response.statusCode = 200;
response.setHeader("Content-Type", "text/css");
response.write(data);
response.end();
});
}else{
send404(response);
return;
}
}
});
//Server listens on port 3000
server.listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
I highly suggest that you use expressjs for better organizing your project and this issue will be gone
I am attempting to create a basic webserver with Node.JS, but running into an issue with properly serving images.
var server = http.createServer(function (request, response){
if(request.url === '/') {
fs.readFile('public/index.html', 'utf8', function(errors, contents){
response.write(contents);
response.end();
});
} else {
fs.readFile("public" + request.url, 'utf8', function(errors, contents){
if (!errors) {
response.end(contents);
} else {
console.log('Failed to read file: /public' + request.url);
response.writeHead(404);
response.end();
}
});
}
});
Everything works fine, apart from if you go to view the image it attempts to download it (which I believe is corrupted - cant open it), which is not what I want, I wish for the images to be served properly in the browser (not via a tag)
Bonus points: I need to be able to correctly give the proper headers (Do I need just a switch statement and set them via that?), as chrome is giving off warnings
Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost/css.css".
You can use expressjs : http://expressjs.com/
const express = require('express')
const app = express()
app.get('/', (req, res) => res.sendFile('public/index.html'))
app.use(express.static('public'))
app.listen(8080, () => console.log('Example app listening on port 8080!'))
NB :
Your code is unsafe : "public" + request.url. Your users can get all files of your server : fs.readFileSync("public/../../../README.txt");
You will get error on parent folder.
Error: ENOENT: no such file or directory, open 'C:\README.txt'.
I am still learning node but there's one thing that I can't find answers anywhere.
I am trying to deploy a simple code to read the content of a URL. It works fine on localhost but when I deploy to my azure app it does not work at all.
When I access the link on the browser it shows a blank screen.
Here's the code
var http = require('http');
var server = http.createServer(function(request, response) {
const url = "http://www.google.com";
response.writeHead(200, {"Content-Type": "text/plain"});
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log("End of response", port);
response.end('End of response.<br/>');
});
});
});
var port = process.env.PORT || 1337;
server.listen(port);
console.log("Server running at http://localhost:%d", port);
When I access the link on the browser it shows a blank screen.
I encountered the similar issue before, I tried to access http://cn.bing.com, but the request would be automatically redirected to https and there is no any response content.
Based on your code, I created my azure web app to check this issue.
app.js:
var http = require('http');
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
http.get("http://www.google.com", res => {
//check the status code
console.log(res.statusCode+','+res.headers['location']);
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log("End of response", port);
response.end(body);
});
}).on('error',(e)=>{ //catch the error
console.error('Got error:'+e);
response.end('Got exception:'+e);
});
});
var port = process.env.PORT || 1337;
server.listen(port);
console.log("Server running at http://localhost:%d", port);
My project contents look like this via KUDU.
TEST:
For verifying the logs, you could Enable diagnostics logging and check your application logs. Also, you could add a iisnode.yml file into your web app root folder and specific your log configurations, details you could follow Debug Node.js Web Apps on Azure.
Additionally, here are some related tutorials, you could refer to them:
http.get(options[, callback])
How to deploy a node.js site into Azure Web App to create a Website
Create a Node.js web app in Azure
I'm tring to read this file in nodejs using fs module.
I'm getting the response twice. let me know what am i doing wrong. Here's my code.
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res) {
fs.readFile('sample.txt', function(err, sampleData) {
console.log(String(sampleData));
//res.end();
});
console.log("The end");
// res.writeHead(200);
res.end();
}).listen(2000);
After hitting the port in browser. I'm getting the response twice in my terminal. Here's the output.
The end
this is sample text for the testing.
The end
this is sample text for the testing.
You are most likely getting it twice because you are accessing http://localhost:2000/ from the browser.
When doing so there are actually two requests being made. Your actual request and the favicon :) both of which are handled by your server.
Have a look into Chrome debugger -> Network
Two log messages will appear: one for / and one for /favicon.ico
You can verify this by adding console.log(req.url);
To avoid this:
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res){
if(req.url === '/'){ // or if(req.url != '/faicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
// res.writeHead(200);
}).listen(2000);
A request is made to favicon.io automatically.
To avoid automatic request to favicon, you can do the following
http.createServer(function(req, res){
if(req.url != '/favicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
}).listen(2000);
O/p =>
The end.
this is sample text for the testing.
You may pipe the file to the client:
fs.createReadStream('sample.txt').pipe(res);
I just started learning Node.js and Express, and I'm currently trying to build a static file server. My question is: How do I prevent node from crashing every time the user inserts a wrong path?
Here's my code:
var express=require('express')
var fs=require('fs')
var app=express()
var server=app.listen(3000, listening)
console.log('Server Started on Port 3000')
function listening(){
console.log('Listening...')
}
app.use(express.static('website'))
app.get('/search/:page', goTo)
function goTo(req, res){
var data=req.params
fs.createReadStream('./website/'+data.page+'.html').pipe(res)
}
Thank you!
With try-catch your app will try to open the specified path. If it fails, your app will send an error instead of crashing.
Try this:
function goTo(req, res) {
var data = req.params;
try{
fs.createReadStream('./website/'+data.page+'.html').pipe(res);
} catch(err) {
res.send(err);
}
}
Hope it helps.