语法知识点:
XMLHttpRequest
XMLHttpRequest
对象基础语法:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'url', true); // true表示异步
xhr.send();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
DOCTYPE html>
<html>
<head>
<title>Ajax基础示例title>
head>
<body>
<button id="loadData">加载数据button>
<div id="content">div>
<script>
document.getElementById('loadData').addEventListener('click', function() {
// 1. 创建XHR对象
const xhr = new XMLHttpRequest();
// 2. 配置请求
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
// 3. 设置响应类型为JSON
xhr.responseType = 'json';
// 4. 发送请求
xhr.send();
// 5. 处理响应
xhr.onload = function() {
if (xhr.status === 200) {
const data = xhr.response;
document.getElementById('content').innerHTML = `
${data.title}
${data.body}
`;
} else {
console.error('请求失败:', xhr.status);
}
};
// 6. 错误处理
xhr.onerror = function() {
console.error('请求出错');
};
});
script>
body>
html>
语法知识点:
Windows/macOS:
node -v
和 npm -v
Linux:
# 使用nvm安装(推荐)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
nvm install --lts
mkdir my-node-app
cd my-node-app
npm init -y
语法知识点:
http
模块createServer()
方法创建服务器listen()
方法启动服务器req
)和响应对象(res
)案例代码:
// 引入http模块
const http = require('http');
// 创建HTTP服务器
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, {'Content-Type': 'text/plain'});
// 根据URL路径返回不同响应
if (req.url === '/') {
res.end('欢迎来到首页\n');
} else if (req.url === '/about') {
res.end('关于我们\n');
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('页面未找到\n');
}
});
// 监听3000端口
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000/');
});
node server.js
npm install -g nodemon
nodemon server.js
直接在浏览器地址栏输入:http://localhost:3000
curl http://localhost:3000
curl http://localhost:3000/about
// server.js
const http = require('http');
const url = require('url');
const querystring = require('querystring');
// 模拟数据库
let users = [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
];
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url);
const path = parsedUrl.pathname;
const query = querystring.parse(parsedUrl.query);
// 设置CORS头
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
// 处理预检请求
if (req.method === 'OPTIONS') {
res.writeHead(204);
res.end();
return;
}
// 路由处理
if (path === '/api/users' && req.method === 'GET') {
// 获取用户列表
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(users));
} else if (path === '/api/users' && req.method === 'POST') {
// 添加新用户
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const newUser = JSON.parse(body);
newUser.id = users.length + 1;
users.push(newUser);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(newUser));
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('API服务器运行在 http://localhost:3000');
});
DOCTYPE html>
<html>
<head>
<title>Node.js + Ajax 示例title>
<style>
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
form { margin: 20px 0; padding: 20px; border: 1px solid #ddd; }
input { margin: 5px 0; display: block; }
style>
head>
<body>
<h1>用户管理系统h1>
<h2>添加用户h2>
<form id="userForm">
<input type="text" id="name" placeholder="姓名" required>
<input type="number" id="age" placeholder="年龄" required>
<button type="submit">添加button>
form>
<h2>用户列表h2>
<table id="userTable">
<thead>
<tr>
<th>IDth>
<th>姓名th>
<th>年龄th>
tr>
thead>
<tbody>tbody>
table>
<script>
// 获取DOM元素
const userForm = document.getElementById('userForm');
const userTable = document.getElementById('userTable').querySelector('tbody');
// 加载用户列表
function loadUsers() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:3000/api/users', true);
xhr.onload = function() {
if (xhr.status === 200) {
const users = JSON.parse(xhr.responseText);
renderUsers(users);
} else {
console.error('加载用户失败:', xhr.status);
}
};
xhr.onerror = function() {
console.error('请求出错');
};
xhr.send();
}
// 渲染用户列表
function renderUsers(users) {
userTable.innerHTML = '';
users.forEach(user => {
const row = document.createElement('tr');
row.innerHTML = `
${user.id}
${user.name}
${user.age}
`;
userTable.appendChild(row);
});
}
// 添加新用户
userForm.addEventListener('submit', function(e) {
e.preventDefault();
const name = document.getElementById('name').value;
const age = document.getElementById('age').value;
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/api/users', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 201) {
loadUsers(); // 刷新列表
userForm.reset(); // 重置表单
} else {
console.error('添加用户失败:', xhr.status);
}
};
xhr.onerror = function() {
console.error('请求出错');
};
xhr.send(JSON.stringify({ name, age: parseInt(age) }));
});
// 初始加载用户列表
loadUsers();
script>
body>
html>
方法 | 描述 |
---|---|
open(method, url, async) |
初始化请求 |
send([body]) |
发送请求 |
setRequestHeader(header, value) |
设置请求头 |
abort() |
取消请求 |
属性 | 描述 |
---|---|
readyState |
请求状态 (0-4) |
status |
HTTP状态码 |
statusText |
状态文本 |
response |
响应体 |
responseText |
响应文本 |
responseType |
响应类型 |
timeout |
超时时间 |
方法/属性 | 描述 |
---|---|
http.createServer([options][, requestListener]) |
创建HTTP服务器 |
server.listen(port[, host][, backlog][, callback]) |
启动服务器 |
request.method |
请求方法 |
request.url |
请求URL |
response.writeHead(statusCode[, statusMessage][, headers]) |
写入响应头 |
response.write(chunk[, encoding][, callback]) |
写入响应体 |
response.end([data][, encoding][, callback]) |
结束响应 |
// 使用Fetch API重写加载用户函数
async function loadUsers() {
try {
const response = await fetch('http://localhost:3000/api/users');
if (!response.ok) throw new Error('Network response was not ok');
const users = await response.json();
renderUsers(users);
} catch (error) {
console.error('加载用户失败:', error);
}
}
npm install express
const express = require('express');
const app = express();
app.use(express.json());
app.get('/api/users', (req, res) => {
res.json(users);
});
app.post('/api/users', (req, res) => {
const newUser = req.body;
newUser.id = users.length + 1;
users.push(newUser);
res.status(201).json(newUser);
});
app.listen(3000, () => {
console.log('Express服务器运行在 http://localhost:3000');
});
通过以上内容,您已经掌握了从Ajax基础到Node.js Web服务器开发的完整知识体系,包括核心语法、实际案例和进阶技巧。这些知识将为您的前后端分离开发打下坚实基础。