react如何查出当前请求路径
在React中获取当前请求路径(URL路径)通常涉及以下几种方法,具体取决于使用场景(前端路由或服务端请求):
使用前端路由(React Router)
若应用使用React Router管理路由,可通过其提供的钩子或属性获取当前路径:
方法1:useLocation钩子(函数组件)

import { useLocation } from 'react-router-dom';
function MyComponent() {
const location = useLocation();
console.log(location.pathname); // 输出当前路径(如 "/about")
return <div>Current path: {location.pathname}</div>;
}
方法2:withRouter高阶组件(类组件)
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
render() {
const { pathname } = this.props.location;
return <div>Current path: {pathname}</div>;
}
}
export default withRouter(MyComponent);
使用浏览器原生API
若需获取浏览器地址栏的完整URL(包括协议、域名等),可直接使用window.location:

const currentPath = window.location.pathname; // 路径部分(如 "/products")
const fullUrl = window.location.href; // 完整URL
服务端请求场景
若需获取HTTP请求的路径(如SSR或API调用),需通过服务端框架(如Express、Next.js)提供的API:
Express示例:
app.get('/api/data', (req, res) => {
console.log(req.path); // 输出请求路径 "/api/data"
});
Next.js API路由:
export default function handler(req, res) {
console.log(req.url); // 输出请求路径
}
注意事项
- 前端方法仅在浏览器环境生效,SSR需结合服务端逻辑。
- 使用
window.location时需确保代码在客户端执行(如通过useEffect或条件检查typeof window !== 'undefined')。
根据具体需求选择合适的方法即可。






