问题
I'm sending an image using flask to react native, I get "200 OK" if I used postman and I also see the image, but when I'm using react native to get the image and display it on the screen I get the "error Unexpected token � in JSON at position 0."
here's the code:
fetch("http://10.0.2.2:5000/api/echo", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
x: 0,
y: 0
})
})
.then(response => response.text())
.then(responseJson => {
console.log(JSON.parse(responseJson));
})
.catch(error => {
console.error(error);
});
};
I don't know what exactly should I write in .then(), I've tried couple of solutions I found on the internet, but none of them worked.
here's the flask code:
@app.route('/api/echo', methods=['GET', 'POST', 'DELETE', 'PUT'])
def add():
while(True):
data = request.get_json()
img = plt.imread('mapflask.png')
plt.figure()
plt.imshow(img)
plt.scatter(100, 20, s=30, c='red', marker='o')
plt.scatter(30, 40, s=30, c='blue', marker='o')
plt.axis('off')
plt.savefig("test100.png", transparent=True,
bbox_inches='tight', dpi=150)
filename = 'test100.png'
return send_file(filename, mimetype='image/jpg')
回答1:
You are sending an image as a response and accepting application/json
in response.
you should do something like this:-
var image
fetch("http://10.0.2.2:5000/api/echo", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
x: 0,
y: 0
})
})
.then(response => response.blob())
.then(images => {
// Then create a local URL for that image and print it
image = URL.createObjectURL(images)
console.log(image)
}) .catch(error => {
console.error(error);
});
};
来源:https://stackoverflow.com/questions/56867734/how-to-get-an-image-from-flask-api-in-react-native