from flask import Flask, request
from flask_cors import CORS
class AiServer(object):
def __init__(self):
server = Flask(__name__)
CORS(server, supports_credentials=True)
server.route('/post', methods=['POST'])(self.post)
server.run(port=8000, threaded=True)
def post(self):
if request.method == "POST":
print("get post")
response_data = request.get_data()
print("response_data", response_data)
return "Hello"
if __name__ == '__main__':
AiServer()
这里一定要设置supports_credentials=True
。
<script>
function createXMLHTTPObject()
{
var XMLhttpFactories = [//兼容不同浏览器和版本的创建函数数组
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject("Msxml2.XMLHTTP")},
function() {return new ActiveXObject("Msxml3.XMLHTTP")},
function() {return new ActiveXObject("Microsoft.XMLHTTP")},
];
var xmlhttp = false;
for (var i = 0; i < XMLhttpFactories.length; i++)
{
try
{
xmlhttp = XMLhttpFactories[i]();
break; //如果成功,则终止循环
}
catch (e)
{
continue; //如果异常,则继续使用下一个创建函数
}
}
return xmlhttp;
}
xmlhttp = createXMLHTTPObject();
var receive_data;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
receive_data = this.responseText
console.log("rece:", this.responseText);
// myObj = JSON.parse(this.responseText);
// console.log(myObj);
}
};
asynchronous_type = false; //True为异步,false为同步
xmlhttp.open("POST", "http://localhost:8000/post", asynchronous_type);
// 发送数据格式:https://www.cnblogs.com/softidea/p/5745369.html # x-www-form-urlencoded
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
obs = {num : 1}
json_data = JSON.stringify(obs)
xmlhttp.send(json_data)
console.log(receive_data)
</script>