本文共 1504 字,大约阅读时间需要 5 分钟。
为了实现前后端的数据交互,首先需要设置一个简单的Express服务器。以下是服务器的配置步骤:
安装Express框架
使用命令行安装Express包:npm install express
创建Express应用
通过代码创建一个Express应用程序:const express = require('express'); const app = express();设置跨域访问权限
为了允许前端请求接触后端服务器,需要配置跨域访问:app.all('*', function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OVERRIDE'); res.header('Content-Type', 'application/json'); next(); });定义路由规则
配置后端接收前端请求并返回数据:app.post('/serve', function(req, res) { const data = { success: 'success' }; res.send(JSON.stringify(data)); });启动服务器
使用指定端口启动服务器:app.listen(8888, function() { console.log('服务器已成功启动!'); });通过AJAX实现前端与后端的数据交互,步骤如下:
创建XMLHttpRequest对象
在前端调用服务器接口时,使用XMLHttpRequest对象:const xhr = new XMLHttpRequest();
配置请求参数
设置请求的方法和URL:xhr.open('POST', 'http://localhost:8888/serve');发送请求数据
将需要发送的数据以字符串形式传递:xhr.send('a=100');处理响应
根据readystatechange事件处理不同状态码:xhr.onreadystatechange = function() { if(xhr.readyState === 4) { if(xhr.status >= 200 && xhr.status < 300) { console.log(xhr.status); console.log(xhr.statusText); console.log(xhr.getAllResponseHeaders); console.log(xhr.response); result.innerHTML = xhr.response.success; } } };通过以上配置,前端页面可以通过AJAX技术与后端Express服务器进行数据交互,实现动态网页更新和数据展示功能。
转载地址:http://yero.baihongyu.com/