Home  >  Article  >  Web Front-end  >  How to call nodejs on the front end

How to call nodejs on the front end

WBOY
WBOYOriginal
2023-05-11 16:46:401604browse

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!

Statement:
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
Previous article:nodejs delete elementNext article:nodejs delete element