Nodejs——axios请求接口及拦截器跳转登录页面
时间: 2023-08-28 18:06:00 浏览: 139
Node.js是一个基于Chrome V8引擎的JavaScript运行环境,可用于开发服务端应用程序。Axios是一个基于Promise的HTTP客户端,用于发送HTTP请求。Axios支持浏览器和Node.js环境。
在Node.js中使用Axios发送HTTP请求,可以通过以下步骤实现:
1. 安装Axios
可以通过npm命令安装Axios:
```
npm install axios
```
2. 发送HTTP请求
可以使用Axios的get、post、put、delete等方法发送HTTP请求。例如:
```
const axios = require('axios');
axios.get('http://localhost:3000/api/user')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
```
3. 添加请求拦截器
可以通过Axios的interceptors属性添加请求拦截器。拦截器可以在发送请求前对请求进行处理。例如,可以在请求头中添加token等信息:
```
axios.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
return Promise.reject(error);
}
);
```
4. 添加响应拦截器
可以通过Axios的interceptors属性添加响应拦截器。拦截器可以在接收到响应后对响应进行处理。例如,可以在响应中检查是否需要跳转到登录页面:
```
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response.status === 401) {
// 跳转到登录页面
window.location.href = '/login';
}
return Promise.reject(error);
}
);
```
以上是使用Axios发送HTTP请求及添加拦截器的基本步骤。在实际应用中,还需要考虑请求的参数、响应的处理等方面。
阅读全文
相关推荐















