我正在尝试将Web上的JSON数据发送到Flask服务器以插入到MongoDB中。当我尝试在JavaScript代码中发出POST请求时,XMLHttpRequest总是返回satus 0,不知道为什么。我尝试了几种方法来执行POST请求并始终获得状态0。我不知道问题是由服务器还是由我的JavaScript代码引起的。
我发出请求的JavaScript函数如下:
var obj = JSON.stringify({name: rname, description: rdescription, image:strimage, exercises:aux});
var xhr = new XMLHttpRequest();
var url = "http://127.0.0.1:5000/addroutine"
xhr.open('POST', url);
xhr.setRequestHeader("Content-type","application/json");
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status == 200){
var json = JSON.parse(xhr.responseText);
console.log(json.name + ", " + json.description + ", " + json.image + ", " + json.exercises)
}
else{
console.log(xhr.status);
}
}
xhr.send(obj)
我已使用以下代码在Python中完成了Flask Server:
from flask import Flask
from flask import request
from pymongo import MongoClient
from bson.json_util import dumps
import json
client = MongoClient('localhost:27017')
db = client['workouts']
collection = db['workouts']
app = Flask(__name__)
@app.route("/addroutine", methods = ['POST'])
def add_routine():
try:
data = json.loads(request.data)
idrutina = data['id']
name = data['name']
description = data['description']
image = data['image']
exercises = data['exercises']
if idrutina and name and description and image and exercises:
collection.insert_one({
"_id" : idrutina,
"description" : description,
"image" : image,
"exercises" : exercises
})
return dumps({'message' : 'SUCCESS'})
except Exception as e:
return dumps({'error' : str(e)})