如何从React Native的Flask API获取图像 [英] how to get an image from flask api in react native
问题描述
我正在使用烧瓶发送图像以响应本机,如果我使用邮递员,我也会看到"200 OK",但是我使用响应本机获取图像并将其显示在屏幕上时,也会显示"200 OK"我在JSON的位置0收到错误意外令牌."
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."
下面是代码:
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);
});
};
我不知道我到底该用.then()写什么,我尝试了一些我在互联网上找到的解决方案,但是没有一个起作用.
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.
这是烧瓶代码:
@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')
推荐答案
您正在发送图像作为响应,并接受application/json
作为响应.
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);
});
};
这篇关于如何从React Native的Flask API获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!