Javascript:如何通过HTTPS和AJAX调用API?

时间:2016-02-27 02:14:28

标签: javascript python ajax ssl tornado

以前我的网站是关于http协议的,所以在我的javascript中这样做:

$.ajax({
                    url: 'http://x.x.x:5000/sthng',
                    type: 'GET',
                    headers: {
                        "Authorization": "Basic " + btoa(uname + ":" + pass)
                    },
                    success: function(result) {
                        console.log(result)
                    }
                 });

但由于http不安全,我转而使用HTTPS。当我尝试访问HTTPS网站时,如何进行ajax调用?

顺便说一下,我正在使用Flask API前面的Tornado Web服务器。我的Tornado服务器代码是这样的:

from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler, RequestHandler, Application
from flask-file import app
import tornado.httpserver

class MainHandler(RequestHandler):
  def get(self):
    self.write("This message comes from Tornado ^_^")

class getToken(tornado.web.RequestHandler):
    def get(self):
        self.write("hello")

tr = WSGIContainer(app)

application = Application([
(r'/', getToken),
(r"/tornado", MainHandler),
(r".*", FallbackHandler, dict(fallback=tr)),
])

if __name__ == "__main__":
  http_server = tornado.httpserver.HTTPServer(application, ssl_options={
        "certfile": "C:/x/key.pem",
        "keyfile": "C:/x/server.key",
  })
  http_server.listen(5000)
  tornado.ioloop.IOLoop.instance().start()

每次Javascript(在AJAX中使用url:'https://x.x.x:5000/sthng)调用API时,这就是我在Tornado中遇到的错误:

ERROR:tornado.application:Exception in callback (<socket.socket fd=344, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('0.0.0.0', 5000)>, <function wrap.<locals>.null_wrapper at 0x000000000499FD90>) Traceback (most recent call last):   
File "C:\Python34\lib\site-packages\tornado\ioloop.py", line 883, in
    start handler_func(fd_obj, events)  
File "C:\Python34\lib\site-packages\tornado\stack_context.py", line 275, in
    null_wrapper  return fn(*args, **kwargs)
File "C:\Python34\lib\site-packages\tornado\netutil.py", line 274, in
    accept_handler callback(connection, address)
File "C:\Python34\lib\site-packages\tornado\tcpserver.py", line 239, in
    _handle_connection do_handshake_on_connect=False) 
File "C:\Python34\lib\site-packages\tornado\netutil.py", line 510, in
    ssl_wrap_socket context = ssl_options_to_context(ssl_options)
File "C:\Python34\lib\site-packages\tornado\netutil.py", line 487, in
    ssl_options_to_context context.load_cert_chain(ssl_options['certfile'],
    ssl_options.get('keyfile', None)) ssl.SSLError: [SSL] PEM lib (_ssl.c:2515)

另外:做卷毛给我这个: curl:(35)与x.x.x:5000

相关的未知SSL协议错误

真的输了!请帮忙。感谢。

1 个答案:

答案 0 :(得分:0)

尝试将数据类型设置为“jsonp”,这有助于我提供跨源请求。

  $.ajax({
        url: "https://x.x.x:5000/sthng/"
        dataType: "jsonp",
        success: function(data) {
          console.log(data)
        }
 });

不需要输入:get as ajax call默认为'get'