后端没有配置跨域,前端如何配置跨域
时间: 2024-02-21 17:35:22 浏览: 55
前端可以通过设置请求头来配置跨域。在发送跨域请求时,在请求头中添加 "Origin" 字段,字段的值为允许跨域访问的域名或 IP 地址。对于常见的跨域请求,可以使用以下方法进行配置:
1. 使用 XMLHttpRequest 或 Fetch API 发送请求时,可以通过设置 `XMLHttpRequest` 对象或 `fetch` 函数的 `headers` 属性来添加请求头。
```javascript
const url = 'http://example.com/api'; // 跨域请求的目标地址
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Origin', 'http://your-frontend-domain.com'); // 设置允许跨域访问的域名
xhr.send();
```
或者使用 Fetch API:
```javascript
const url = 'http://example.com/api'; // 跨域请求的目标地址
fetch(url, {
headers: {
'Origin': 'http://your-frontend-domain.com' // 设置允许跨域访问的域名
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```
2. 如果使用基于 axios 的 HTTP 客户端,可以通过在请求配置对象中设置 `headers` 属性来添加请求头。
```javascript
const axios = require('axios'); // 导入 axios 库
const url = 'http://example.com/api'; // 跨域请求的目标地址
axios.get(url, {
headers: {
'Origin': 'http://your-frontend-domain.com' // 设置允许跨域访问的域名
}
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
```
以上是一些常见的前端跨域配置方法,请根据你使用的 HTTP 请求库或工具适配。另外,还需确保后端服务已经配置了跨域访问的规则,否则即使前端配置了也无法生效。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)