如何实现跨域?

1 个回答

  • 小龙
    谎言不会伤人,真相才是快刀。
    跨域请求通常发生在浏览器中,因为浏览器有同源策略,防止不同域名之间的交互。实现跨域的方法有多种,常见的方法包括JSONP、CORS和代理方式。 ### 1. JSONP 方式 JSONP(JSON with Padding)是一种通过 `<script>` 标签的 `src` 属性来实现跨域的技术。JSONP 只支持 GET 请求。 ```html <!DOCTYPE html> <html> <head> <title>JSONP Example</title> <script> function handleResponse(response) { console.log(response); } function loadScript(url) { var script = document.createElement('script'); script.src = url; document.body.appendChild(script); } window.onload = function() { loadScript('http://example.com/jsonp?callback=handleResponse'); }; </script> </head> <body> <h1>JSONP Example</h1> </body> </html> ``` 服务器需要返回类似如下的内容: ```javascript handleResponse({"message": "Hello, world!"}); ``` ### 2. CORS 方式 CORS(Cross-Origin Resource Sharing)是一个W3C标准,允许服务器设置特定的HTTP头来允许跨域请求。 #### 简单请求 浏览器发送的请求头: ```http GET /resource HTTP/1.1 Host: api.example.com Origin: http://yourdomain.com ``` 服务器的响应头: ```http HTTP/1.1 200 OK Access-Control-Allow-Origin: http://yourdomain.com Content-Type: application/json ``` #### 预检请求 浏览器的预检请求头: ```http OPTIONS /resource HTTP/1.1 Host: api.example.com Origin: http://yourdomain.com Access-Control-Request-Method: POST Access-Control-Request-Headers: X-Custom-Header ``` 服务器的预检响应头: ```http HTTP/1.1 200 OK Access-Control-Allow-Origin: http://yourdomain.com Access-Control-Allow-Methods: GET, POST, PUT Access-Control-Allow-Headers: X-Custom-Header Access-Control-Allow-Credentials: true Access-Control-Max-Age: 1728000 ``` 浏览器的实际请求头: ```http POST /resource HTTP/1.1 Host: api.example.com Origin: http://yourdomain.com Content-Type: application/json X-Custom-Header: value ``` 服务器的实际响应头: ```http HTTP/1.1 200 OK Access-Control-Allow-Origin: http://yourdomain.com Content-Type: application/json ``` ### 3. 代理方式 代理方式通常使用服务器来代理跨域请求,例如使用Nginx作为代理服务器。 #### Nginx 配置: ```nginx server { listen 88; server_name yourdomain.com; location /api { proxy_pass http://api.example.com; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header Access-Control-Allow-Headers 'X-Custom-Header'; } } ``` #### 前端代码: ```javascript fetch('http://yourdomain.com/api/resource', { method: 'GET', credentials: 'include' }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ### 总结 - **JSONP** 适用于简单的GET请求跨域,但只支持GET请求。 - **CORS** 是现代浏览器支持的标准跨域方式,支持复杂请求,适用于大多数场景。 - **代理方式** 是通过服务器中转请求来实现跨域,适用于复杂场景或需要兼容旧浏览器的情况。
    发布于 2024-08-07 22:51 •IP属地 贵州
    举报
    评论
    收藏