[英]How to make a GET request from node server to Flask API
我很难将我的节点 API 连接到我的 Flask API,我不断收到Error: connect ETIMEDOUT 10.209.234.2:80
我有一个 Node 应用程序,它对 Flask API 执行简单的获取请求,如下所示:
var options = {
method: 'GET',
headers: {'Content-Type': 'application/json'},
url: 'http://localhost:5000/api/v1/counts/health-check',
}
await axios(options)
.then(function (resp) {
console.log('SUCCESS, response below')
console.log(resp)
})
.catch(function (error) {
console.log('ERROR, error below')
console.log(error)
})
.then(function() {
console.log("Not an error but see below")
})
我的 Flask API 路由构建如下:
from flask import Flask, request, jsonify, make_response
from flask_marshmallow import Marshmallow
from marshmallow import fields
import psutil
from datetime import datetime
from flask_cors import CORS
app = Flask(__name__)
ma = Marshmallow(app)
app.config['CORS_HEADERS'] = 'Content-Type'
CORS(app)
@app.route('/api/v1/counts/health-check', methods = ['GET'])
def health_check():
try:
print("Endpoint {} called".format('/api/v1/counts/health-check'))
uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time())
uptime = uptime.total_seconds()
message = 'OK'
timestamp = datetime.now()
response = jsonify({"uptime": uptime,
"message": message,
"timestamp": timestamp})
return make_response(response, 201)
except Exception as e:
print('The following exception occured: {}'.format(e))
当我通过 postman 调用 Flask 路由时,它工作得很好,但通过节点服务器它一直超时。 我究竟做错了什么?
提前致谢!
既然您提到使用 Postman,您是否尝试过使用它为 API 请求生成代码? 您可以生成您需要的 Javascript 并在您的解决方案中尝试。
我找到了解决方案,它很简单:不要使用 axios。 使用一个简单的 promise 调用解决了它并且 GET 请求有效。
这样的事情应该这样做:
let url = "http://127.0.0.1:5000/api/v1/counts/health-check";
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}).then(response => console.log(response.json()));
我不是 100% 确定为什么会这样,但我猜这与 axios 默认使用代理的事实有关。 希望这对将来有类似问题的人有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.