后端路由在 url 匹配路径时即被触发,无论请求来自浏览器直接导航还是前端 fetch 调用;但二者在用途、能力与交互模式上存在根本差异:导航主要用于页面跳转与 html 渲染,而 fetch 专为程序化数据交互设计,支持任意 http 方法、自定义头、json 体及错误处理。
在 Web 开发中,一个常见的误解是认为“只有调用 fetch() 才会触发后端路由”。实际上,只要客户端(浏览器)发起符合该路由规则的 HTTP 请求,服务端就会执行对应逻辑——无论是用户在地址栏输入 /restaurants 并回车,还是前端 JavaScript 执行 fetch('/restaurants'),Express 的 app.get('/restaurants', ...) 回调都会被调用,并返回 ALL_RESTAURANTS 数组的 JSON 数据。
然而,触发相同路由 ≠ 实现相同目的。关键区别在于:
例如,以下代码不仅获取餐厅列表,还实现了错误处理与加载反馈:
const getRestaurants = async () => {
try {
const response = await fetch('/restaurants', {
method: 'GET',
headers: { 'Accept': 'application/json' }
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response
.status}`);
}
const restaurants = await response.json();
return restaurants;
} catch (err) {
console.error('Failed to fetch restaurants:', err);
throw err;
}
};
// 使用示例(React 中)
useEffect(() => {
getRestaurants().then(data => setRestaurants(data));
}, []);总之,后端路由是服务端逻辑的入口,而 fetch 是前端主动调用该入口的“工具”。导航是被动的、面向文档的;fetch 是主动的、面向数据的。理解这一分层,才能构建出响应迅速、体验流畅、可维护性强的现代 Web 应用。