我正在学习这个Udemy react-native课程,但发现它有点过时了。
课程部分9与RapidAPI AI Picture Colorizer一起工作以选择base64编码图像。但是看起来API已经更新了,不再使用base64,而是使用图片上传。
我使用的是react-native-imagepicker,但我不确定如何更新代码,以便从设备的库中选择一个图像并按照RapidAPI文档的读取方式上传。
以下是RapidAPI示例代码:
import axios from "axios";
const form = new FormData();
form.append("image", "");
form.append("renderFactor", "25");
const options = {
method: 'POST',
url: 'https://ai-picture-colorizer.p.rapidapi.com/colorize-api-bin-mjbcrab',
headers: {
'content-type': 'multipart/form-data; boundary=---011000010111000001101001',
'x-rapidapi-host': 'ai-picture-colorizer.p.rapidapi.com',
'x-rapidapi-key': '[MY-API-KEY]'
},
data: '[form]'
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});这是我的代码:
import React, {Component} from 'react';
import {View, Text, Image, StyleSheet} from 'react-native';
import {Button} from 'react-native-elements';
import ProgressBar from 'react-native-progress/Bar';
import {launchImageLibrary} from 'react-native-image-picker';
import axios from 'axios';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
menu: true,
dataSource: null,
loading: true,
base64: null,
fileName: null,
};
}
selectGallaryImage() {
const options = {
includeBase64: true,
};
launchImageLibrary(options, response => {
if (response.didCancel) {
console.log('User canceled Image');
} else if (response.error) {
console.log('Image picker error');
} else if (response.customButton) {
console.log('User pressed custom Button');
} else {
this.setState(
{
base64: response.assets[0].base64,
fileName: response.assets[0].fileName,
},
() => console.log('base64 fileName ', this.state.fileName),
);
this.goForAxios();
}
});
}
goForAxios() {
const {fileName} = this.state;
const form = new FormData();
form.append('image', fileName);
form.append('renderFactor', '10');
this.setState({menu: false});
console.log('Starting request');
axios
.request({
method: 'POST',
url: 'https://ai-picture-colorizer.p.rapidapi.com/colorize-api-bin-mjbcrab',
headers: {
'content-type':
'multipart/form-data; boundary=---011000010111000001101001',
'x-rapidapi-host': 'ai-picture-colorizer.p.rapidapi.com',
'x-rapidapi-key': '[MY-API-KEY]',
},
data: '[form]',
})
.then(response => {
this.setState({
loading: false,
dataSource: response.data,
});
})
.catch(error => {
console.error(error);
});
}
...
}我已经联系了应用编程接口的作者,他们建议我参考RapidAPI文档,但我似乎无法解决这个问题。
我一直收到Error: Request failed,状态代码为500,在RapidAPI中运行Test Endpoint返回OK,但返回“There no example response for this endpoint”。
谢谢你的帮助。
发布于 2021-09-15 21:42:10
当服务器由于意外情况而找不到任何合适的状态代码时,它通常会返回500状态代码。我不是React Native专家,但我是来帮忙的。
您正在使用react-native-image-picker,它已经在响应中返回了Base64值。因此,不是:
base64: response.assets[0].base64,尝尝这个
base64: response.data,如果它仍然不起作用,您可以使用另一个提供类似功能的API。在属于同一类别的RapidAPI集线器上可以找到数以千计的API。例如,使用此Image Colorization接口。它允许您将图像作为URL进行传递。
https://stackoverflow.com/questions/69198885
复制相似问题