How to call nodejs on the front end
As a front-end developer, we often encounter situations where we need to call the back-end interface. As a fast and scalable JavaScript runtime, Node.js has the ability to handle I/O-intensive operations. Therefore, calling the backend interface of Node.js is a good choice. In this article, we will introduce how the front-end calls Node.js methods.
1. Use Ajax technology to call Node.js
Ajax is one of the most common methods for the front-end to call the server-side interface. The implementation of the code is relatively simple, suitable for one-way information transmission, and does not require refreshing the entire page, achieving an effect similar to partial refresh, reducing the burden on the server. The following is a code example of using Ajax to call Node.js:
1. Preparation
First, you need to write a back-end service in Node.js, which based on the request sent by the front-end, Return the appropriate response. The following sample code demonstrates how to implement a Node.js backend service:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World
');
});
server.listen(3000, '127.0.0.1');
console.log('Server running at http://127.0. 0.1:3000/');
2. Send a request
In the front-end code, we can call the back-end service of Node.js through Ajax technology. The following is a simple sample code:
function ajaxCall() {
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("myDiv").innerHTML = this.responseText; } }; xmlhttp.open("GET", "http://localhost:3000", true); xmlhttp.send();
}
Here, we use the XMLHttpRequest object to open the connection with the server through the open() function Connection, send() function can send requests to the server. The request here is a GET request, which is used to obtain the server's response.
2. Use WebSocket to call Node.js
WebSocket is a full-duplex communication protocol, mainly used to realize the transmission of real-time data. Through WebSocket, the front-end can conduct two-way communication with the server in real time. The following is a code example of using WebSocket to call Node.js:
1. Preparation
First, you need to write a WebSocket back-end service in Node.js, which will establish a connection with the front-end WebSocket response. The following is a simple demo code:
const http = require('http');
const WebSocket = require('ws');
const server = http.createServer();
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('A new client connected!'); ws.on('message', (message) => { console.log(`Received message => ${message}`); ws.send(`Hello, you sent => ${message}`); }); ws.send('Welcome to the WebSocket server!');
});
server.listen( 3000, () => {
console.log('Server started on port 3000 :)');
});
2. Send a request
In the front-end code, we can establish a connection with Node.js through WebSocket Connect, send requests to Node.js and receive responses. The following is a simple demonstration code:
const socket = new WebSocket('ws://localhost:3000');
socket.onopen = () => {
console.log('Connection established!'); socket.send('I am a new client!');
};
socket.onmessage = (event) => {
console.log(`Received message => ${event.data}`);
};
3. Use Fetch to call Node.js
Fetch API is a new network request API based on Promise. Compared with Ajax, it provides a simpler API and more convenient operations. The following is a code example of using Fetch to call Node.js:
1. Preparation
First, you need to write a backend service in Node.js, which is based on the request sent by the front end. Return the appropriate response. The following sample code demonstrates how to implement a Node.js backend service:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World
');
});
server.listen(3000, '127.0.0.1');
console.log('Server running at http://127.0. 0.1:3000/');
2. Send a request
In the front-end code, we can call the back-end service of Node.js through the Fetch API. The following is a simple demonstration code:
fetch('http://localhost:3000')
.then(response => response.text()) .then(data => console.log(data)) .catch(err => console.error(err));
Here, we use the Fetch API to send a request and pass the then() function and catch() function to handle the response. Since the Fetch API returns a Promise object, we can use the then() function and catch() function to handle success or failure.
Summary:
This article introduces how the front-end calls Node.js. Through the three methods of Ajax, WebSocket and Fetch API, the front-end can easily interact with Node.js. Of course, in actual development, there are various ways of interacting between the front and back ends, and we should choose the appropriate way to develop according to the actual situation.
The above is the detailed content of How to call nodejs on the front end. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

Functional components in Vue.js are stateless, lightweight, and lack lifecycle hooks, ideal for rendering pure data and optimizing performance. They differ from stateful components by not having state or reactivity, using render functions directly, a

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.
