axios跨域访问练习,拦截*.action请求的全部代码
时间: 2023-11-22 22:29:33 浏览: 44
以下是使用axios实现跨域访问并拦截*.action请求的完整代码示例,包括前端和后端:
前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Axios跨域访问练习</title>
</head>
<body>
<h1>Axios跨域访问练习</h1>
<div id="result"></div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
axios.interceptors.request.use(config => {
// 判断请求是否为*.action请求
if (/\.action$/.test(config.url)) {
// 设置请求头信息
config.headers['X-Requested-With'] = 'XMLHttpRequest';
// 添加请求参数
config.params = { ...config.params, _t: Date.now() };
}
return config;
}, error => {
return Promise.reject(error);
});
axios.get('http://localhost:3000/api/user.action', { withCredentials: true })
.then(response => {
document.getElementById('result').innerText = JSON.stringify(response.data);
})
.catch(error => {
console.error(error);
});
</script>
</body>
</html>
```
后端代码:
```javascript
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: true,
credentials: true,
}));
app.get('/api/user.action', (req, res) => {
// 处理业务逻辑
res.send({ name: 'Alice' });
});
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
```
在运行该代码时,需要先启动后端服务器,通过命令`node server.js`启动。然后,通过浏览器打开前端页面,即可进行跨域访问并拦截*.action请求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)