Node.js interacts with the frontend via HTTP request/response, WebSocket, and Socket.IO: Set up a Node.js server and define routes. The front end sends HTTP requests or establishes connections using WebSocket or Socket.IO. The Node.js server handles the request and returns a response or sends data over a live connection.
Node.js Interaction with the front-end
Node.js is a method for building server-side applications JavaScript runtime environment. It can interact with front-end technologies such as HTML, CSS, and JavaScript to provide dynamic and interactive web applications.
Interaction methods
Interaction between Node.js and the front-end can be carried out in the following ways:
Implementation steps
1. Create server:
<code class="javascript">const express = require('express'); const app = express(); const server = app.listen(3000);</code>
2. Define route:
<code class="javascript">app.get('/', (req, res) => { res.send('Hello from Node.js!'); });</code>
3. Handle front-end requests:
<code class="javascript">app.post('/submit-form', (req, res) => { const data = req.body; // 处理表单数据... });</code>
4. Use WebSocket:
<code class="javascript">const WebSocket = require('ws'); const wss = new WebSocket.Server({ server }); wss.on('connection', (ws) => { // 与客户端建立 WebSocket 连接... });</code>
5 . Using Socket.IO:
<code class="javascript">const socketIO = require('socket.io'); const io = socketIO(server); io.on('connection', (socket) => { // 与客户端建立 Socket.IO 连接... });</code>
Front-end code example:
<code class="javascript">// 发送 HTTP 请求 fetch('/submit-form', { method: 'POST', body: JSON.stringify({ name: 'John' }), }) .then((res) => res.json()) .then((data) => console.log(data)); // 建立 WebSocket 连接 const socket = new WebSocket('ws://localhost:3000'); socket.onopen = () => console.log('Connected to WebSocket'); // 使用 Socket.IO const socket = io(); socket.on('connect', () => console.log('Connected to Socket.IO'));</code>
The above is the detailed content of How nodejs interacts with the front end. For more information, please follow other related articles on the PHP Chinese website!