Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从api获取reactjs中的图像?_Javascript_Node.js_Reactjs_Fetch Api - Fatal编程技术网

Javascript 如何从api获取reactjs中的图像?

Javascript 如何从api获取reactjs中的图像?,javascript,node.js,reactjs,fetch-api,Javascript,Node.js,Reactjs,Fetch Api,在使用JWT令牌验证之后,我正在从NodeJSAPI获取一个图像。 我在浏览器网络标题中得到200 ok响应,图片可以在预览中看到,但我无法在我的应用程序中使用它 我肯定做错了什么。请让我知道从API显示图像的正确方式。 在我的后端节点上,我使用res.sendFile发送文件 class Card extends Component { constructor({props, pic, token}) { super(props, pic, token); this.state = {

在使用JWT令牌验证之后,我正在从NodeJSAPI获取一个图像。 我在浏览器网络标题中得到200 ok响应,图片可以在预览中看到,但我无法在我的应用程序中使用它

我肯定做错了什么。请让我知道从API显示图像的正确方式。 在我的后端节点上,我使用res.sendFile发送文件

class Card extends Component {
 constructor({props, pic, token}) {
super(props, pic, token);
this.state = { 
  pic: pic,
};

urlFetch(data) {
 fetch(data, { 
 headers: new Headers({
 'authorization': `Bearer ${this.props.token}`, 
 'Content-Type': 'application/json'
 })
})
.then(response => {
 if (response.statusText === 'OK') {
  return data   // OR return response.url
  }
 })
}

render() {
const { pic } = this.state;

 return (
        <div>
          <img style={{width: 175, height: 175}} className='tc br3' alt='none' src={ this.urlFetch(pic) } />
        </div>
       );
      }
     }
类卡扩展组件{
构造函数({props,pic,token}){
超级(道具、图片、令牌);
this.state={
图:图,,
};
urlFetch(数据){
获取(数据,{
标题:新标题({
'authorization':`Bearer${this.props.token}`,
“内容类型”:“应用程序/json”
})
})
。然后(响应=>{
如果(response.statusText==='OK'){
返回数据//或返回响应.url
}
})
}
render(){
const{pic}=this.state;
返回(
);
}
}

这是我尝试过的获取数据的方法:

componentDidMount(){
    fetch('https://www.yoursite.com/api/etc', {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    })
    .then((response) => {
      return response.text();
    })
    .then((data) => {
      console.log( JSON.parse(data) )
      this.setState{( pic: JSON.parse(data) )}
    })
}
然后在你的img中

src={ this.state.pic }

我找到了答案。这是:


我能够使用与此类似的模式在React中使用后端调用渲染图像:
React钩子
axios
URL.createObjectURL

我使用
URL.createObjectURL(blob)
方法,并使用axios配置
{responseType:'blob'}
确保数据类型适合

const ImageComponent = (imageIds) => {
  const [images, setImages] = React.useState([])

  React.useEffect(() => {
    async function getImage (id) {
      let imageBlob
      try {
        imageBlob = (await axiosClient.get(`/api/image/${id}`, { responseType: 'blob' })).data
      } catch (err) {
        return null
      }
      return URL.createObjectURL(imageBlob)
    }
    async function getImages () {
      const imageArray = []
      for (const id of imageIds) {
        imageArray.push(await getImage(id))
      }
      setImages(imageArray)
    }

    getImages()
  }, [imageIds])

  return images.map((img, i) => {
    return <img src={img} alt={`image-${i}`} key={i} />
  })
}
const ImageComponent=(imageid)=>{
常量[images,setImages]=React.useState([])
React.useffect(()=>{
异步函数getImage(id){
让imageBlob
试一试{
imageBlob=(等待axiosClient.get(`/api/image/${id}`,{responseType:'blob'})).data
}捕捉(错误){
返回空
}
返回URL.createObjectURL(imageBlob)
}
异步函数getImages(){
常量imageArray=[]
for(ImageID的常量id){
imageArray.push(等待getImage(id))
}
设置图像(图像阵列)
}
getImages()
},[ImageID])
返回images.map((img,i)=>{
返回
})
}
[编辑]:如果您的api是受保护的路由,请确保您的axios http客户端已使用令牌初始化

 var myHeaders = new Headers();
 myHeaders.append("response", "image/jpeg");
 myHeaders.append("psId", "");
 myHeaders.append("x-api-key", "Z7dwTzHQrklCh7bvSWqhNrDTPZiLblYS");
 myHeaders.append(
    "Authorization",
    "Bearer token"
 );

var raw = "";

var requestOptions = {
  method: "GET",
  headers: myHeaders,
  //body: raw,
  redirect: "follow",
};
let response = await fetch(
  "YourURL",
  requestOptions
)
.then((response) => response)
.then((result) => result)
.catch((error) => console.log("error", error));

 res = await response.blob();
然后,在html或jsx文件中的图像标记中,您可以按如下方式进行操作:

 <img src={window.webkitURL.createObjectURL(res)} />


src={pic}
应该可以工作。@hurricane它不会工作。获取的图像和状态属性
pic
之间没有链接。在
urlFetch
中没有发生
setState
callback@hurricane正如我提到的,我在后端使用JasonWebToken获取图像。api返回图像url或图像文件本身?@roxyPoxxy我可以在浏览器网络->预览中看到图像。只有在后端授权成功的情况下,我才会在获取中返回图像url。请重新阅读此问题。这与承诺无关。我必须在我的应用程序中使用从后端发送的图像。您是否尝试过此操作。设置状态{(pic:data)}在您的fetch方法中,然后src={this.state.pic}?那么我如何调用函数来请求带有令牌的图像?我通常在ComponentDidMount中执行此操作,而不是在response.text和parse中执行此操作。然后((response)=>{return response.json()})。然后((data)=>{console.log(“响应是”+data) })