本文介绍了来自本地主机的API正常,但使用Ajax失败-ERR_CONNECTION_REFUSED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Flask的API非常简单(我们称其为api.py):

I have a very minimal API (let's call it api.py) using Flask :

from flask import Flask, request
from flask_restx import Resource, Api
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app)
api = Api(app)


@api.route('/hello')
class HelloWorld(Resource):
        def get(self):
                return {"hello" : "world"}


if __name__ == '__main__':
        app.run(port=5000)
}`

然后我运行:python3 api.py,没有错误然后在另一个命令行上查询API

I then run : python3 api.py, no errorOn another command line, I then query the API

curl http://localhost:5000/hello

这给了我正确的答案:{"hello":"world"}Flask App的侧面说:127.0.0.1--[21/May/2020 22:55:38]"GET/hello HTTP/1.1" 200-对我来说没关系

which give me the right answer : {"hello": "world"}On its side, the Flask App says : 127.0.0.1 - - [21/May/2020 22:55:38] "GET /hello HTTP/1.1" 200 -Which seems ok to me

然后,我构建一个JS/Ajax查询来从网页查询API:

I then build a JS / Ajax Query to query the API from a WebPage :

$.ajax({
    url: "http://localhost:5000/hello"
    , type: "GET"
    , contentType: "application/json"
    , dataType: "json"
    , success: function(data) {
         console.log(data)
    }
})

当我访问触发Ajax调用的网页时,出现以下错误消息:GET http://localhost:5000/hello net :: ERR_CONNECTION_REFUSED

When I access the Web Page that fires the Ajax call, I get the following error message :GET http://localhost:5000/hello net::ERR_CONNECTION_REFUSED

我知道这是CORS问题.问题是我确实测试了SO和其他帮助论坛的所有技巧,但都没有成功...我确实尝试过:

I understand that is a CORS issue. The problem is that I did test ALL the tricks from SO and other help forums with no success...I did try :

from flask_cors import CORS
app.run(host="0.0.0.0", debug=True)
app.run(host="0.0.0.0", debug=False)
@cross-origin
...

什么都没用,我仍然有这个ERR_CONNECTION_REFUSED

Nothing works, I still have this ERR_CONNECTION_REFUSED

感谢您在此问题上的任何帮助,因为我对此问题感到头疼...

Thanks for any help on that subject, as I am loosing my head with that problem...

推荐答案

您的Ajax调用不应指向本地主机.将其替换为EC2实例的URL.

Your ajax call shouldn't be pointing to localhost. Replace it with the URL of the EC2 instance.

这篇关于来自本地主机的API正常,但使用Ajax失败-ERR_CONNECTION_REFUSED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 23:11