Using .createServer to make a public website - node.js

So I have a file I want to host from my computer, and I want to be able to listen at the port for various reasons. I'm using
const port = [number]
http.createServer((req, res) => {
let responseCode = 404;
let content = '404 Error';
const urlObj = url.parse(req.url, true);
if (urlObj.query.code) {
const accessCode = urlObj.query.code;
}
if (urlObj.pathname === '/') {
responseCode = 200;
content = fs.readFileSync('./index.html');
}
res.writeHead(responseCode, {
'content-type': 'text/html;charset=utf-8',
});
res.write(content);
res.end();
})
.listen(port);
and all that good stuff makes it where I can have a local file, http://localhost:[number]. However, I'm not exactly sure how I can use this same method for hosting on an online website, one in which I upload my code to the website then have the website started from my computer (using the create server). Does anyone know how to basically create a server that's not private/local, but instead is public (and yes I can use a web host).

I recommend using the express framework as it greatly simplifies serving static files. It would be as simple as the following:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static(__dirname + '/public'));
app.listen(port , () => {
console.log(`Server is running at port ${port}`);
});
With above code all that's left to do is to create folder called public in your app directory where you place your html/css/js files.

Related

Automatic exit - NodeJS https webserver

To elaborate on the question in the title,
I have made a simple app with js that runs on a node server. I have a thumbdrive that contains a folder and a start.bat file. Start.bat, as the name implies, switches the directory to my server folder and starts the server. Start.bat also starts another process that opens the edge browser to localhost in kiosk mode. When a user starts start.bat, the app will appear on the screen with the server running in the background. When the user exits the edge browser, they are then required to CTRL + C out of the server cmd prompt to properly shut down the server.
I need a system which effectively automatically shuts down the server after the Edge browser has been closed. I am not sure if it is possible to tie together the closing of the browser and the node server and am yet to find a solution online. If anyone has any ideas regarding possible fixes to my problem I would love to hear it!
https-server.js
const https = require("https");
const path = require("path");
const fs = require("fs");
const ip = require("ip");
const process = require("process");
const app = express();
const port = 443;
process.chdir("..");
console.log("Current working dir: " + process.cwd());
var rootDir = process.cwd();
//determines what folder houses js, css, html, etc files
app.use(express.static(rootDir + "/public/"), function (req, res, next) {
const ip = req.ip;
console.log("Now serving ip:", "\x1b[33m", ip, "\x1b[37m");
next();
});
//determines which file is the index
app.get("/", function (req, res) {
res.sendFile(path.join(rootDir + "/public/index.html"));
});
var sslServer = https.createServer(
{
key: fs.readFileSync(path.join(rootDir, "certificate", "key.pem")),
cert: fs.readFileSync(path.join(rootDir, "certificate", "certificate.pem")),
},
app
);
//determines which port app (http server) should listen on
sslServer.listen(port, function () {
console.log(
"Server has successfully started, available on:",
"\x1b[33m",
ip.address(),
"\x1b[37m",
"listening on port:",
"\x1b[33m",
+port,
"\x1b[37m"
);
console.log("CTRL + C to exit server");
sslServer.close();
});
Will provide any needed information.
Have an endpoint registered to exit the process
app.get('/shutdown', (req, res, next) => {
res.json({"message": "Received"});
next();
}, () => {
process.exit();
});
Then register a listener for onbeforeunload to do a request to this endpoint.
let terminateCmdReceived = false;
async function shutdown(e) {
let response;
if (!terminateCmdReceived) {
e.preventDefault();
try {
response = await fetch('http://localhost:3000/shutdown');
const json = await response.json();
if(json.message === "Received") {
terminateCmdReceived = true;
window.close();
}
} catch (e) {
console.error("Terminate Command was not received");
}
}
}
window.onbeforeunload = shutdown

Nodejs, nodemon app crashed (screenshot inside)

don't understand what's wrong with my server and code. I am passing tutorial and did everything just like in the video but still have the problem
Image
It seems like you are using https connection without handling TLS certificates passing.
Here is a code snippet to make you access your openweathermap API without configurating certificates.
const express = require('express')
const https = require('https')
const app = express()
app.get("/", function(req, res) {
const url = "<openweathermap>"
var options = require('url').parse( /**String*/ url );
options.rejectUnauthorized = false;
https.get(options, function(response) {
console.log(response);
}).on( 'error',function ( e ) {
console.log(err);
}).end();
res.send("Sever up and running");
}
app.listen(3000, function(){
console.log("Server running on port 3000";
}
I would suggest to read more on how to setup certificates for HTTPS in Node.JS,
refer this doc. for more details.

In Node.js is it possible to create a virtual folder if so how

In Node.js is it possible to create a virtual folder if so how?
Some context for needing a virtual folder:
Have a project in Node.js that is a middleware is listinning to port 400 for example so can make request to my endpoints as follow http://{IP}:400/?p={%22getWebhooks%22:true}. The port 400 is open to make external requests.
In the same server there is another middleware that is .NET/C# that is using port 80 and it only works inside the server (its blocked from the outside)
This Project serves to integrates images among other data, those images are saved in folder under that .NET project where in the Node.js need's to have access to those images in the folder (to avoid having to ask for another port to be open to the outside/ public IP)
The Node.js project is in C:\nodeProject
http://{IP}:400/?p={%22getWebhooks%22:true}
The Images folder is in C:\inetpub\wwwroot\{.netProject}\back_office\resources
to avoid needing another open port for The IIS for example port 200 to serve the images
http://{IP}:200/resources/images.jpg
wanted to serve the images using Node.js
http://{IP}:400/resources/images.jpg
Not using express.js using the http module
var server = http.createServer(function (req, res) {
Don't know if node-static package can be use for this use-case...
Thanks for any information that points me in the right direction.
As #Molda refered by using the package node-static solved my probleam but had to use inside my app as in the code bellow where query === null is condition to see if the request doesn't have paramter's then its a image to be serve other wise it a normal request to endpoint of my Node.js app middleware.
var staticNode = require('node-static');
var fileServer = new staticNode.Server('C:/inetpub/wwwroot/example/back_office/resources/');
var server = http.createServer(function (req, res) {
let body = []
req.on('error', (err) => {
console.error(err);
}).on('data', chunk => {
body.push(chunk);
}).on('end', () => {
let bodyResponse;
if (body.length > 0) {
bodyResponse = JSON.parse(body);
//console.log(body);
console.log(bodyResponse);
}
//var page = url.parse(req.url).pathname;
var query = url.parse(req.url).query
var params = querystring.parse(query);
if(query === null){
fileServer.serve(req, res);
}else{
if ('p' in params && isJSON(params['p'])) {
var p = JSON.parse(params['p']);
switch (Object.keys(p)[0]) {
...
}
} else {
res.write(JSON.stringify({
"errorMessage": "invalid request format"
}));
res.end();
}
}
}).resume();
});

How get response from express server for ajax query in nuxtjs

I'm want to get data from the node/express server after send ajax query from any page of the nuxtjs app.
Usually, for getting and sending ajax query in PHP server, I'm do like this $_GET['var']; echo json_encode('Server got data');
Now I want to use node server express for saving data in mongodb.
When I trying to send a query, response return full code of file test.js.
File index.vue
methods: {
onServer() {
this.$axios.get('/server/test').then(res => {
console.log('res', res.data)
})
}
}
File test.js
var express = require('express');
var app = express();
app.get('*', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
File server/index.js
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
I'm a new user node, please help me!
Your main issue is that you are targeting "test.js" in your axios url. This is why it responds with the file rather than what the get route should respond with.
So try with:
this.$axios.get('http://nuxt-profi/server/test').then(...
and see what you get. You should also be able to access that in the browser, just go to your url http://nuxt-profi/server/test and it should show your "Hello World" reponse.
However I can't be sure how you have set all this up. Are you running this as development? In which case maybe you should access it as http://localhost:3000/server/test but maybe you have virtual hosts configured like this. Also, is this a separate backend api or are you trying this as server middleware?
If this doesn't help please give us more info about your project setup and we'll go from there.

Axios can GET but not POST to the same URL

I'm building a react app
In one component I'm writing this GET request which works:
In another component I'm writing this POST request:
Which then returns this 404 error:
And I have no idea how my GET works but my POST returns 404:not found when I'm requesting the same file both times?
UPDATE:
I'm running a node.js server now but it's a bit of a frankenstein's monster as this really isn't an area I have an understanding of. Does anyone know what I'm doing wrong?
// Server setup from node.js website
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// Trying to listen for data from React app to feed into JSON (broken)
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.post("/scene-setup.json", function(request, response) {
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
});
app.listen(3001);
// Updating JSON file with "obj" (working)
var jsonfile = require('jsonfile')
var file = './scene-setup.json'
var obj = {name: 'JP'}
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
Axios is used for making HTTP requests. So, you should have a backend server running that can handle these requests. I am not sure what exactly is the data that you want to save. If you need access to that data, should be saving it on the backend.
If you want to save some data just on the client side, HTML5 filesystem API might be something you want to look at. It can manage some data in the limited sandboxed part of user's filesystem.

Resources