I have some data that I want to store locally and to be able to pull it dynamically, maybe in another session or after the browser was closed and all browser data was cleared.
I run the site with http-server CLI command and navigate to localhost to access it from the browser.
How can I send data to the server side so the server side will save the data as a file?
I tried to do an ajax post request to see if something happens in the console, but it just returned 404 and nothing came up in the console.
The docs don't mention anything about post requests: https://www.npmjs.com/package/http-server
PS: I have to run this with http-server, this is an offline project.
You will not be able to do this with http-server alone, because http-server can only serve static content and cannot be used to run any code on the server side.
You will have to write a backend yourself, possibly using a framework like Express, Hapi, Restify, Loopback etc. and serve your static files that you need with your new backend, or keep it served as you do now but then you will probably need to take CORS into account if you use different ports for your data saving/retrieving endpoints and your static content - unless you run a reverse proxy that makes it all appear on the same host name and port.
You can use the file system to save the data or you can use a database - either a standalone database like Mongo or Postgres or an embedded database like SQLite or Loki.
For examples on how to serve static content in your own backend see:
How to serve an image using nodejs
You should use express for this kind of stuff. You can easily make methods that handle certain requests.
Here is an exmaple on how to handle a get request by just sending some data
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
And you can use the fs api from node itself to write data.
var fs = require('fs')
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
Note: the fs example uses arrow functions. You can find more information here
Related
Here is my HTML code in index.html.
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="stuff()">Click</button>
<script>
async function stuff() {
await connectToServer();
}
async function connectToServer() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(this.responseText);
};
xhttp.open('GET', 'C:/Users/myName/myFolder/index.js', true);
xhttp.send();
return;
}
</script>
</body>
</html>
Then, here is my backend code in index.js.
const express = require('express');
const axios = require('axios');
const port = process.env.PORT || 8080;
const app = express();
app.get('/', (req, res) => {
res.sendFile('C:/Users/myName/myFolder/views/index.html');
});
app.listen(port, () => console.log(`Listening on port ${port}`));
I can type node index.js on the command line and run this program and go to http://localhost:8080/ . When I do this, the html page shows up as intended. However, when I click the button in order to make a GET request to the server side, I get a console error saying Not allowed to load local resource: file:///C:/Users/myName/myFolder/index.js . I'm using Google Chrome by the way.
I know that it is a security thing, and that you are supposed to make requests to files that are on a web server (they begin with http or https). I suppose then, my question is:
How do I make it so that my server file index.js can be viewed as being on a server so that I can call functions on the backend from my frontend?
You have to make an HTTP request to a URL provided by the server.
The only URL your server provides is http://localhost:8080/ (because you are running an HTTP server on localhost, have configured it to run on port 8080, and have app.get('/', ...) providing the only path.
If you want to support other URLs, then register them in a similar way and write a route to handle them.
The express documentation will probably be useful.
You should not need to load your server-side code into the browser. It's server-side code. It runs on the server. It isn't client-side code. It doesn't run in the browser. The browser does not need access to it.
If you want to load some actual client-side JS from the server, then use <script src="url/to/js"></script> (and not Ajax) and configure express' static middleware.
Let's improve your current flow by separating your backend API process from frontend hosting process. While backend can, it's not good in serving static html files (especially for local development purposes).
Run your backend as usual, node index.js. But as soon as this command will become more complicated, you will probably want to use npm scripts and do just npm start)
Run separate server process for frontend. Check out parcel, snowpack, DevServer. It can be as easy as npx parcel index.html, but this command is likely to change frequently with your understanding of your tool features.
To call backend, just add an API endpoint to an express app (just like you already did for serving static content), and call it, using backend process URL.
Usually, you will see your app on http://localhost/ and it should do requests to http://localhost:8080/.
If for some strange reason you will want to dynamically download js file from your server to execute it, you just need to serve this file from your frontend hosting process. In order to do so, different development servers have different techniques, but usually you just specify file extensions and paths you want to be available.
After editing frontend files, you will see hot-reload in browser. You can achieve the same for node process with various tools (start googling from nodemon)
If you find this way of operating not ideal, try to improve it, and check what people already did in this direction. For example, you can run two processes in parallel with concurrently.
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.
My goal is this: JS but server-side. My solution, the obvious, node.js. I've used node.js quiet a bit. Mainly for an application, not a web server. The only reason I need to do server-side JS is that I need to use a library that connects to the Discord API. So I have a little test .js file with my node.js in it. It just prints text if it works. Basic. What I need it to do is whenever someone goes to https://example.com/something, it runs the node.js script and if the script ends up with printing "hello", then https://example.com/something will say "hello".
I've done some research on this, I've found ways to deploy a node.js app, which I know how to do. I can't really find anything that I'm looking for though.
You can use express to run a webserver on nodejs
Install express by running "npm install express" in your project folder through command prompt
Create a app.js file with the following code
var express = require('express'); // load the express library
var app = express(); // create an instance of express
var child_process = require('child_process'); //load the child_process module
app.get("/something", function(req, res) { // Setup a router which listens to the site http://localhost/something
child_process.fork("./yourCodeFile.js"); // Launch your code file
});
app.listen(80);
Run node app.js to listen to web connections
Then you put your code into the yourCodeFile.js which has to be be in the same folder as the app.js file, even better you could just write all your code in the app.js code as long as you keep it inside the function inside app.get
You should take a look at cloud-based lambda functions and platforms like AWS Lambda, which run a script in response to an HTTP request. They are relatively new and the architecture used to support this is being called "serverless", which is a simple term, albeit a bit of a misnomer. There are various tools out there to help you build these systems, such as the similarly named Serverless framework, though you can typically still use more traditional server frameworks that you are probably more comfortable with. Either way, you are not responsible for managing any server, including starting it or stopping it.
In terms of constructing a response that you are happy with, you can of course respond with any arbitrary string you want. See the AWS example of a Node.js handler.
exports.myHandler = function(event, context, callback) {
callback(null, "Hello, world!");
}
Lambda functions can also return binary data and work well with static storage systems like Amazon S3. For example, the function can be run in response to the creation of static assets.
Your code should look like this:
const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
const pathName =url.parse(req.url).pathname;
if (pathName == '/something') {
res.end('Hello World\n');
} else {
res.end('Please visit /something \n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
You should run your file with node youfile.js And when you do curl http://127.0.0.1:3000 you will see
Please visit /something
But when you do curl http://127.0.0.1:3000/something you will see
Hello World
I am trying to build a real-time Django application.
Because of the way my hosting service works, I am unable to start a Websocket server in parallel of my Django server.
I managed to have user-to-user interactions by creating an express server on a separate NodeJS website with socket.io, and having clients on the Django server also connect to the remote socket.io server.
However, I'dlike to have my Django server directly send events to users. To do this, I would like to create a connection between the Django server and the NodeJS server. Something like that in python:
socket = io("http://socket.io.server")
socket.emit('eventForUsers')
Is there anyway for me to achieve this?
The only information I found seemed to require me to run a parallel server from my Django app, which I can't do because my host doesn't allow me to run long-term processes.
It really depends what is the most simple solution for you, and what are your requirements. (If you want realtime bidirectional messaging then I suggest to use the socket.io-client instead of the POST example)
POST (GET,PUT,...)
You can (for example) use POST requests from your Django to Node
Django: python example (there are other ways to perform a POST to Node from Django)
reqParams = {"action":"doThis","data":"put the pizza in the oven"}
import requests
requests.post('http://ip:port/route', params = reqParams)
Node example : Listens for post at /route (express) and prints the params of the Django request
var express = require('express');
var app = express();
app.post('/route', function (req, res) {
console.log(req.query); res.end();
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Then you can use the data in req.params to perform action like broadcasting something to the socket.io clients (or a specific client)
This can also be done the other way around, performing requests to send data from Node to Django using POST (GET,...)
Socket.io-client in Django
Another (easier) solution is to include the socket.io-client in your Django webapp so it connects to your Node socket.io server as a client when the webapp is opened by browsers.
(using javascript in django)
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://ip:port');
socket.on('connect', function(){alert("Hello World!");});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
</script>
More Resources :
1. JavaScript (Django Docs)
2. Including the static files in your template
I'm a node.js begginer . Let's say I have an apache server(XAAMP) and node.js installed in C:\Program Files\nodejs\nodejs.exe on windows 7.
How can I run node.js in my apache server to simulate my code?
I mean, I know how to write node.js code but what I don't know how it's work on my server?
Apache server don't need for Node.js.
For create your own Node.js server:
Download and install Node.js
Create file hello.js:
var http = require("http");
var server = http.createServer().listen(3000); // beter way for create
server.on("request", function(req, res){
res.writeHead(200, {"Content-Type": "text/plain"});
// for view at page http://localhost:3000
res.write("Hello world");
res.end();
});
server.on("listening", function(){
// for view in console
console.log("Listen: 3000...");
});
In terminal go to dir where file hello.js and type:
node hello.js
Open your browser and point it at http://localhost:3000/. This should display a web page that says:
Hello world
A basic HTTP server
Node.js Manual & Documentation
If you like to work with a replacement for XAAMP you should finally take a look at MEAN.io.
At NpmJS.org you will find different solutions for most of your needs.
and like Reagan Gallant commented you should take a look at this famous stackoverflow post (if you need ideas).
NodeSchool indeed is a good entry point for your fist steps. After that npmjs will make sense and finally you will love Mean.io
You just make it use a different port than Apache is using (for example port 3000 which is the default for express-js and others) -- that is assuming that you don't need the two to work together.
If you do need them to work together, you add a forwarding module to Apache and configure the forwarding in Apache of certain URL to go to your local port for node-js