简体   繁体   中英

communication between html and node.js (basics)

I'm completely new to web application programming and stuck on creating the backend to my html-file. So far I have created a nice user interface in html and javascript, and I have read tutorials on node.js. However, all the tutorials focus on the server-side programming. I don't understand how to connect my html-file with the node.js application. So, please help me to get started by explaining a simple example:

Let's assume we have a website that contains two fields and text that can be dragged from one field into another.

<head>
    <style>
        #div1,
        #div2 {
            width: 100px;
            height: 35px;
            margin: 10px;
            padding: 10px;
            border: 1px solid red;
        }
    </style>
    <script>
        function allowDrop(ev) {
            ev.preventDefault();
        }

        function drag(ev) {
            ev.dataTransfer.setData("text", ev.target.id);
        }

        function drop(ev) {
            ev.preventDefault();
            var data = ev.dataTransfer.getData("text");
            ev.target.appendChild(document.getElementById(data));
        }

        function appendDragText() {
            // read myFile. HOW DO I DO THIS???
            textFromFile = "My draggable text is in field 2";
            if (textFromFile == "My draggable text is in field 1") {
                document.getElementById("div1").appendChild(document.getElementById("dragText"));
            } else {
                document.getElementById("div2").appendChild(document.getElementById("dragText"));
            }
        }
    </script>
</head>

<body>
    <div draggable="true" ondragstart="drag(event)" id="dragText">Draggable</div>
    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
    <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
    <script>appendDragText()</script>
</body>

Also, there needs to be a node.js file called "writeFile.js" that performs some node.js-magic.

var fs = require('fs');
var fieldNumber = 2; // HOW CAN I LOOK INTO THE BROWSER TO KNOW WHERE MY TEXT IS?
var textForFile = "My draggable text is in field " + fieldNumber
fs.writeFile('mynewfile.txt', textForFile, function (err) {
  if (err) throw err;
});

How do I get those two pieces of code (the html file and the node.js file) connected?

The background of my problem is as follows: I'm creating an organisation tool for my boss in html and javascript. It's a calender where employees are assigned to different tasks for each day. The employees are represented as rectangles on a table and those rectangles can be dragged between the cells of that table. When the browser is opened it needs to read the information for each employee stored in a text-file or database. And each change to the calender needs to be saved into the text-file or database.

I hope I'm on the right track with node.js and wait for your help.

On the serverside you need to create an API, preferably RESTful. Then you do a POST or PUT request to the API to store your changes (via AJAX). And use GET requests (again AJAX) to fetch the stored data from the API.

Take a look at swagger.io (or other similar tools) to get started. Their editor has an option to "generate" a barebone API in NodeJS from the specs you provide.

You should create a node js server that will serve your page and handle your app logic.

I would recommend you tu use ExpressJS as it is really easy to implement and learn.

Your server could look like so :

  • A root view that serves your static page
  • A post route that handles your "node magic"

Use AJAX to make the call to your post view. Get the request body through a bodyparser package Handle the success response client side.

Here's a quick example of how your server code should look like :

const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();

/* Middlewares */
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));

/* Routes */
app.get('/', function (req, res) {
    res.sendFile('index.html');
});

app.post('/write-file', function (req, res) {
    const body = req.body; // your request body

    // your "magical" code

});

/* 3, 2, 1, Launch ! */
app.listen(process.env.PORT || 3000, function() {
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM