前端通过HTTP请求调用Node.js微服务,流程包括:1. 使用Express搭建提供RESTful接口的Node服务;2. 前端用fetch或axios发起请求获取或提交数据;3. 配置CORS解决跨域问题;4. 可选axios优化请求处理。

前端调用 Node.js 微服务,本质上是通过 HTTP 请求与后端 API 进行通信。Node.js 作为微服务运行时,通常暴露 RESTful 或 GraphQL 接口,前端通过浏览器的网络能力(如 fetch 或 axios)发起请求获取数据或执行操作。下面详细介绍完整流程和具体示例。
先确保你的 Node.js 服务已经启动并提供可用接口。常用框架有 Express、Koa 等。以下是一个使用 Express 创建简单用户接口的例子:
// server.js
const express = require('express');
const app = express();
app.use(express.json());
// 模拟用户数据
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// GET 接口:获取所有用户
app.get('/api/users', (req, res) => {
res.json(users);
});
// POST 接口:添加新用户
app.post('/api/users', (req, res) => {
const newUser = req.body;
users.push(newUser);
res.status(201).json(newUser);
});
app.listen(3000, () => {
console.log('Node 微服务运行在 http://localhost:3000');
});
运行 node server.js 后,服务将在 3000 端口监听请求。
前端可以使用原生 fetch 或第三方库如 axios 调用上述接口。以下是 HTML + JavaScript 的简单页面示例:
立即学习“前端免费学习笔记(深入)”;
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>调用 Node 微服务</title>
</head>
<body>
<h2>用户列表</h2>
<ul id="userList"></ul>
<button onclick="fetchUsers()">加载用户</button>
<button onclick="addUser()">添加用户</button>
<script>
// 获取用户列表
async function fetchUsers() {
try {
const response = await fetch('http://localhost:3000/api/users');
const users = await response.json();
const listEl = document.getElementById('userList');
listEl.innerHTML = '';
users.forEach(user => {
const li = document.createElement('li');
li.textContent = user.name;
listEl.appendChild(li);
});
} catch (err) {
console.error('请求失败:', err);
}
}
// 添加新用户
async function addUser() {
const newName = prompt('输入用户名:');
if (!newName) return;
try {
const response = await fetch('http://localhost:3000/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: Date.now(), name: newName })
});
if (response.ok) {
alert('用户添加成功');
fetchUsers(); // 刷新列表
}
} catch (err) {
console.error('提交失败:', err);
}
}
</script>
</body>
</html>
前端和 Node 服务若不在同一域名或端口,浏览器会阻止请求。需在 Node 服务中启用 CORS:
const cors = require('cors');
app.use(cors()); // 允许所有来源
或安装 cors 包:npm install cors
这样前端就能从其他域名(如 http://localhost:5500)安全调用 Node 接口。
axios 更简洁且兼容性好。前端引入方式:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
替换 fetch 调用:
async function fetchUsers() {
try {
const response = await axios.get('http://localhost:3000/api/users');
console.log(response.data);
} catch (err) {
console.error(err);
}
}
基本上就这些。只要 Node 服务正常运行、接口可用、CORS 配置正确,前端就能顺利调用。实际项目中建议统一请求封装、处理 loading 和错误状态,提升用户体验。
以上就是前端怎么调用Node微服务_前端调用Node.js微服务的完整流程与示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号