415例外Cherrypy Web服务

415例外Cherrypy Web服务,第1张

415例外Cherrypy Web服务

我已经意识到问题实际上是关于 CORS的飞行前请求 。CORS 规范为简单的CORS请求定义了以下条件:

  • 方法:
    GET
    HEAD
    POST
  • 头:
    Accept
    Accept-Language
    Content-Language
    Content-Type
  • 教改尝试型头值:
    application/x-www-form-urlenpred
    multipart/form-data
    text/plain

否则,CORS请求并不简单,请在实际请求之前使用预检OPTIONS请求,以确保其符合要求。这是CORS的最佳做法。

因此,如果您想保持简单,则可能需要恢复正常状态

application/x-www-form-urlenpred
。否则,您需要正确处理预检请求。这是工作示例(不要忘记添加
localhost
别名)。

#!/usr/bin/env python# -*- coding: utf-8 -*-'''Add localhost alias, `proxy` , in /etc/hosts.'''import cherrypyconfig = {  'global' : {    'server.socket_host' : '127.0.0.1',    'server.socket_port' : 8080,    'server.thread_pool' : 8  }}def cors():  if cherrypy.request.method == 'OPTIONS':    # preflign request     # see http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0    cherrypy.response.headers['Access-Control-Allow-Methods'] = 'POST'    cherrypy.response.headers['Access-Control-Allow-Headers'] = 'content-type'    cherrypy.response.headers['Access-Control-Allow-Origin']  = '*'    # tell CherryPy no avoid normal handler    return True  else:    cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'cherrypy.tools.cors = cherrypy._cptools.HandlerTool(cors)class App:  @cherrypy.expose  def index(self):    return '''<!DOCTYPE html>      <html>      <head>      <meta content='text/html; charset=utf-8' http-equiv='content-type'>      <title>CORS AJAX JSON request</title>      <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>      <script type='text/javascript'>        $(document).ready(function()        {          $('button').on('click', function()          { $.ajax({   'type'        : 'POST',   'dataType'    : 'JSON',   'contentType' : 'application/json',   'url'         : 'http://proxy:8080/endpoint',   'data'        : JSON.stringify({'foo': 'bar'}),   'success'     : function(response)   {     console.log(response);     } });          })        });      </script>      </head>      <body>        <button>make request</button>      </body>      </html>    '''  @cherrypy.expose  @cherrypy.config(**{'tools.cors.on': True})  @cherrypy.tools.json_in()  @cherrypy.tools.json_out()  def endpoint(self):    data = cherrypy.request.json    return data.items()if __name__ == '__main__':  cherrypy.quickstart(App(), '/', config)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5016423.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存