简体   繁体   中英

Javascript: How to call an API over HTTPS and AJAX?

Previously my website was on http protocol, so doing this in my javascript worked:

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

But as http is not secure, I shifted to HTTPS. How should I make the ajax call when I'm trying to access HTTPS website?

Btw I'm using Tornado web server which is in front of Flask API. My Tornado server code is like this:

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()

This is the error I'm getting in Tornado every time Javascript (using url: ' https://xxx:5000/sthng ' in AJAX) calls the API:

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)

Also: doing curl gives me this: curl: (35) Unknown SSL protocol error in connection to xxx:5000

Really lost here! Please help. Thanks.

Try setting the datatype to "jsonp", that's helped me for cross-origin requests.

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

no need of type: get as ajax call defaults to 'get'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM