ajax 如何禁止 预检请求,如何跳过“选项”预检请求?
时间: 2024-06-08 10:10:28 浏览: 8
要禁止预检请求,可以在发送 AJAX 请求时设置 `XMLHttpRequest` 对象的 `setRequestHeader` 方法,将 `Content-Type` 设置为 `application/x-www-form-urlencoded` 或 `multipart/form-data`。
例如:
```
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(formData);
```
要跳过“选项”预检请求,可以在发送 AJAX 请求时设置 `XMLHttpRequest` 对象的 `withCredentials` 属性为 `true`,并且将 `Access-Control-Allow-Origin` 头部设置为允许的域名。
例如:
```
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api', true);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Access-Control-Allow-Origin', 'https://example.com');
xhr.send(JSON.stringify(data));
```
注意,跳过“选项”预检请求可能会存在安全风险,因此建议只在必要情况下使用。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)