Home Web Front-end JS Tutorial Node implements simple front-end and back-end interaction

Node implements simple front-end and back-end interaction

Dec 21, 2017 am 11:13 AM
node interaction rear end

Node is a skill that must be learned in the front-end. We all know that node uses js as the back-end. Before learning node, we need to understand how node realizes front-end and back-end interaction. This article brings you a simple front-end and back-end interaction of Node (explanation with examples). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look, I hope it can help everyone.

Here is a simple interaction between native ajax and node. Friends who have just learned node can take a look. On the one hand, you understand how the server and client interact, and on the other hand, you are more familiar with node development.

Post the code first: (If you are interested, you can copy it locally and run it yourself)

The html of the main page

index.html:

<!doctype>
<html>
 <head>
  <meta charset="utf-8">
  <title></title>
 </head>
 <body>
  <button id="btn1">food</button>
  <button id="btn2">other</button>
  <h1 id="content"></h1>

  <script type="text/javascript" src="./client.js"></script>
 </body>
</html>
Copy after login

Next is the server-side code. The running method is to enter the command in the node environment: node server.js

server.js:

let http = require('http'); 
let qs = require('querystring'); 

let server = http.createServer(function(req, res) {
 let body = ''; // 一定要初始化为"" 不然是undefined
 req.on('data', function(data) {
  body += data; // 所接受的Json数据
 });
 req.on('end', function() { 
  res.writeHead(200, { // 响应状态
   "Content-Type": "text/plain", // 响应数据类型
   'Access-Control-Allow-Origin': '*' // 允许任何一个域名访问
  });
  if(qs.parse(body).name == 'food') {
   res.write('apple');
  } else {
   res.write('other');
  } 
  res.end();
 }); 
});

server.listen(3000);
Copy after login

The qs module introduced is used to parse JSON

req.on('data', callback); // Monitor the client's data and execute the callback function once data is sent

req.on('end', callback); // Data reception completed

res //Response

Client js (the function is responsible for some DOM operations and sending ajax requests)

client.js:

let btn1 = document.getElementById('btn1');
let btn2 = document.getElementById('btn2');
let content = document.getElementById('content');

btn1.addEventListener('click', function() {
 ajax('POST', "http://127.0.0.1:3000/", 'name='+this.innerHTML);
});

btn2.addEventListener('click', function() {
 ajax('POST', "http://127.0.0.1:3000/", 'name='+this.innerHTML);
});

// 封装的ajax方法
function ajax(method, url, val) { // 方法,路径,传送数据
 let xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
  if(xhr.readyState == 4) {
   if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
    content.innerHTML = xhr.responseText;
   } else {
    alert('Request was unsuccessful: ' + xhr.status);
   }
  }
 };

 xhr.open(method, url, true); 
 if(val)
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
 xhr.send(val);
}
Copy after login

This simple interaction is like this. In fact, when we first learn a back-end language, the first thing we do is to write a front-end and back-end interactive program. This will help us better understand the division of labor between the front and back ends.

run method:

First run server.js, and then open html to request a response.

Related recommendations:

Related content summary about front-end and back-end interaction

##Node.js+Koa framework realizes front-end and back-end interaction

PHP front-end and back-end interaction

The above is the detailed content of Node implements simple front-end and back-end interaction. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

12 points to note when sharing interface design documents 12 points to note when sharing interface design documents Apr 24, 2023 am 10:58 AM

Recently, when I was reviewing the interface document, I found that the parameter defined by a small partner was an enumeration value, but the interface document did not give the corresponding specific enumeration value. In fact, how to write interface documents well is really important. Today, Brother Tianluo brings you 12 points to pay attention to in interface design documents~

Turn on split-screen interaction in win11 Turn on split-screen interaction in win11 Dec 25, 2023 pm 03:05 PM

In the win11 system, we can enable multiple monitors to use the same system and operate together by turning on split-screen interaction. However, many friends do not know how to turn on split-screen interaction. In fact, just find the monitor in the system settings. The following is Get up and study. How to open split-screen interaction in win11 1. Click on the Start menu and find "Settings" 2. Then find the "System" settings there. 3. After entering the system settings, select "Display" on the left. 4. Then select "Extend these displays" in the multi-monitor on the right.

In-depth understanding of generics in golang (Generic) In-depth understanding of generics in golang (Generic) Apr 11, 2023 pm 07:20 PM

What this article brings to you is an in-depth understanding of generics in golang? How to use generics? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

See all articles