[关闭]
@gzm1997 2018-06-10T06:35:43.000000Z 字数 3755 阅读 1425

aiohttp的跨域问题

aiohttp cors


跨域

以前使用flask框架的时候一直都是没有前后端分离 现在使用aiohttp框架 并且前端使用vue 前后端分离 因此出现了跨域的问题

不同浏览器对跨域的支持也是不一样的 支持跨域的浏览器主要有

标准的跨域请求默认是不发送任何的cookies的 如果需要把cookies作为请求的一部分 需要将请求 比如js底层的XMLHttpRequest请求的withCredentials属性设置为true

xhr.withCredentials = true;

相应的服务端那边需要设置Access-Control-Allow-Credentials为true来允许cookies的传送

Access-Control-Allow-Credentials: true

withCredentials属性将让request包含来自远程域的任何cookies 同时它也设置任何来自远程域的cookies 要注意这些cookies还遵循同域标准的 因此你的javascrpt代码不能访问来自document.cookie或者responset header的cookies 这些cookies只可以被远程域控制

除了javascrip代码需要根据浏览器对cors支持程度不一样需要恰当的作出跨域请求 例如如下代码

  1. // Create the XHR object.
  2. function createCORSRequest(method, url) {
  3. var xhr = new XMLHttpRequest();
  4. if ("withCredentials" in xhr) {
  5. // XHR for Chrome/Firefox/Opera/Safari.
  6. xhr.open(method, url, true);
  7. } else if (typeof XDomainRequest != "undefined") {
  8. // XDomainRequest for IE.
  9. xhr = new XDomainRequest();
  10. xhr.open(method, url);
  11. } else {
  12. // CORS not supported.
  13. xhr = null;
  14. }
  15. return xhr;
  16. }
  17. // Helper method to parse the title tag from the response.
  18. function getTitle(text) {
  19. return text.match('<title>(.*)?</title>')[1];
  20. }
  21. // Make the actual CORS request.
  22. function makeCorsRequest() {
  23. // This is a sample server that supports CORS.
  24. var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';
  25. var xhr = createCORSRequest('GET', url);
  26. if (!xhr) {
  27. alert('CORS not supported');
  28. return;
  29. }
  30. // Response handlers.
  31. xhr.onload = function() {
  32. var text = xhr.responseText;
  33. var title = getTitle(text);
  34. alert('Response from CORS request to ' + url + ': ' + title);
  35. };
  36. xhr.onerror = function() {
  37. alert('Woops, there was an error making the request.');
  38. };
  39. xhr.send();
  40. }

服务端也需要一定的cors支持
在客户端和服务端之间的传输 一般客户端需要作出一些附加的headers和附加的请求 这些请求一般是隐藏的 但是可以抓包发现
image_1cfk1f1dvn7bpjdc6k3q61gc3m.png-29.4kB

跨域请求分类

  1. 简单跨域请求
  2. 不简单跨域请求

处理简单跨域请求

简单跨域请求这样命名的原因是因为他们可以让浏览器不做处跨域请求也可以访问到 比如JOPN请求或者html的表单form 这些情况不存在跨域的问题

JSONP是什么

一个有效的服务器response

  1. Access-Control-Allow-Origin: http://api.bob.com
  2. Access-Control-Allow-Credentials: true
  3. Access-Control-Expose-Headers: FooBar
  4. Content-Type: text/html; charset=utf-8

其中以下是跨域请求必须的

Access-Control-Allow-Origin这个属性必须在server response的headers中 这个属性用来说明哪个域可以访问你的数据 如果缺少会导致跨域的失败 如果像让所有的域可以访问你的数据 那么可以使用*

Access-Control-Allow-Credentials默认来说 cookies是不可以包含在跨域请求中 使用这个属性说明cookies可以包含在跨域请求头部中 这个属性跟上面说到的withCredentials协同工作的(withCredentials是js客户端这边设置的 Access-Control-Allow-Credentials是服务端这边设置的)

Access-Control-Expose-Headers 在js的XMLHttpRequest 2对象中可以使用getResponseHeader()的方法来获取一个response的header 在跨域请求中 getResponseHeader()方法只可以获取简单的response header 简单的response header被定义为如下

如果像客户端可以获取其他的headers就需要使用Access-Control-Expose-Headers这个属性了

处理不简单跨域请求
不简单跨域请求在客户端看起来跟简单跨域请求差不多 但是它在有运行两个附加的请求

  1. 首先客户端会发送一个preflight request 这个请求用于获取服务端的允许来发送真正的请求
  2. 获取允许之后 客户端发送真正的请求
  3. 因为preflight request是可以被缓存的 所以不需要每次请求都发送一次preflight request

跨域例子

有以下api

http://localhost:8080/api/product/1

以上api可以获取以下json个格式对象

  1. {
  2. "id": 1,
  3. "name": "pork",
  4. "picture": "https://demo.pork.png",
  5. "price": 53,
  6. "description": "this is a pork",
  7. "rating": 0.8,
  8. "amount": 100,
  9. "likes": 0,
  10. "tag_id": 1,
  11. "sales_permonth": 382
  12. }

在一个html的script中使用jquery的$.get访问上面的api 因为需要从不同域名或者不同端口下加载资源 所以浏览器出于安全考虑会阻止这个api的访问 值得一提的是postman并不是严格按照这个标准的

测试跨域的html

  1. <html>
  2. <head>
  3. <title>cors_test</title>
  4. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
  5. <script type="text/javascript">
  6. $(document).ready(function () {
  7. $("#submit").click(function() {
  8. $.get("http://localhost:8080/api/product/1", function(data, status) {
  9. alert("data:" + data + "\nStatus:" + status);
  10. });
  11. });
  12. });
  13. </script>
  14. </head>
  15. <body>
  16. <button id="submit">submit</button>
  17. </body>
  18. </html>

结果 出现跨域请求被禁止的报错
image_1cfjvf6ui2ohpq1fbh19kjftm9.png-78.9kB


aiohttp的跨域问题解决

因为aiohttp框架本身是不支持跨域的 所以我们需要使用一个拓展包aiohtto_cors

pip安装

pip install aiohttp_cors

具体使用方法请看aiohttp_cors

我系统分析与设计项目选择解决详情
image_1cfk4pnuuoi31aan1rmn1nr58s91g.png-85.8kB

结果 跨域请求成功
image_1cfk4ucj71ao11suj1r13j0taer1t.png-82.1kB

最后附加flask跨域问题解决方法flask_cors

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注