首页 > 解决方案 > 为什么反应'stl-viewer'没有加载我的私人自定义python烧瓶api提供的stl文件

问题描述

如果这不是问这个问题的正确地方,请告诉我。

一些背景:我有一个 python/flask API,它将根据请求提供相关数据和 STL 文件。根据需要启用 CORS。在该服务器运行的情况下,我通过在地址栏中放置下载文件的链接进行了测试。这成功下载了正确的文件。此外,我将链接放在“react-stl-obj-viewer”库中,并按预期在那里查看我的 STL 模型。所以我确信自定义 API 工作正常。

可能没用 - 但相关的 API 背景代码:

    # @login_required
    def get_model(part_id):
        part = Repo().find_part(part_id)
        if part:
            try:
                file_path = '\\'.join(part["File_Path"].split('\\')[0:-1])
                print(file_path)
                print(part["Name"])
                return send_from_directory(file_path, part["Name"])
            except:
                json_response({'error': f"Failed to complete request for STL model {part_id}"}, 405)
        else:
            return json_response({'error': 'project not found'}, 404)

问题:随着服务器为 python API 和 react 应用程序运行,我多次实例化以下组件。


  constructor(props) {
    super(props);

    this.state = {stlLink: "http://localhost:5000/parts/models/part.stl"}
  }

  render(){
    return ( 
      <div style={{width: 200, height:200, color: "#eb4034"}} >
       
       <STLViewer
          url={this.state.stlLink}
          width={400}
          height={400}
          modelColor='#B92C2C'
          backgroundColor='#EAEAEA'
          rotate={true}
          orbitControls={true}
        />
      </div>
    )
  }
}

在每个实例上都有一个加载动画 - 很好。但我在 API 上看不到任何流量 - 不好。所以我的零件永远不会被加载到查看器中。

我尝试将服务器中请求的方法从 GET 更改为 POST,没有任何改变。我不确定还有什么可以尝试的,因为这感觉像是应该“正常工作”的东西。这就是为什么我在这里:) 有人有什么建议吗?

标签: reactjs

解决方案


我遇到了和你一样的问题。试试这个代码,它对我有用......

import React, { Component } from 'react';
import STLViewer from '../../src/STLViewer';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      color: '#FF0000',
      model: undefined
    };

    this.clickBlue = this.clickBlue.bind(this);
    this.clickRed = this.clickRed.bind(this);
  }

  clickBlue(e) {
    e.preventDefault();
    this.setState({ color: '#0000FF' });
  }

  clickRed(e) {
    e.preventDefault();
    this.setState({ color: '#FF0000' });
  }

  onChange = ({ target }) => {
    const { files } = target;
    const reader = new FileReader();
    reader.readAsArrayBuffer(files[0]);
    reader.onload = () => {
      this.setState({ model: reader.result });
    };
  };

  render() {
    return (
      <div>
        <input id="image-file" type="file" onChange={this.onChange} />
        <STLViewer
          modelColor={this.state.color}
          lights={[[0.5, 1, -1], [1, 1, 1]]}
          rotate={true}
          model={this.state.model}
        />
        <button onClick={this.clickRed}>red</button>
        <button onClick={this.clickBlue}>blue</button>
      </div>
    );
  }
}
export default App;

推荐阅读