Axios error when doing a POST request of a .txt file

打印 上一主题 下一主题

主题 1030|帖子 1030|积分 3090

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题意:在利用Axios发送.txt文件的POST请求时出现的错误


问题背景:

I am working on a project with Flask and React and more specifically, right now I am working on an API endpoint that has the utility of receiving a .txt file from the frontend, and then it would run a script that analyzes data from that .txt and saves plots related to the analysis.
我正在利用Flask和React开发一个项目,更详细地说,现在我正在处理一个API端点,它的功能是从前端接收一个.txt文件,然后运行一个脚本来分析该.txt中的数据,并生存与分析相关的图表。

Here is the API endpoint at the backend:
后端的API端点如下:
  1. @analysis_ns.route('/upload', methods=["POST", "GET"])
  2. class ChatAnalysisUploadResource(Resource):
  3.     def get(self):
  4.         return {"message": "This endpoint is only for file uploads via POST."}, 405
  5.     #@jwt_required()
  6.     def post(self):
  7.         """Upload a chat file, process it and return the image URLs"""
  8.         try:
  9.             if 'file' not in request.files:
  10.                 abort(400, description="No file part")
  11.             file = request.files['file']
  12.             if file.filename == '':
  13.                 abort(400, description="No selected file")
  14.             if file and allowed_file(file.filename):
  15.                 filename = secure_filename(file.filename)
  16.                 file_path = os.path.join(UPLOAD_FOLDER, filename)
  17.                 file.save(file_path)
  18.                 # Procesa el archivo y genera las imágenes
  19.                 process_chat_file(file_path)
  20.                 image_paths = ['static/mensajes_enviados.png', 'static/emojis.png']
  21.                 missing_images = [path for path in image_paths if not os.path.exists(path)]
  22.                 if missing_images:
  23.                     abort(500, description=f"Imagen no encontrada: {missing_images}")
  24.                 image_urls = {
  25.                     'urls': [
  26.                         url_for('static', filename='mensajes_enviados.png', _external=True),
  27.                         url_for('static', filename='emojis.png', _external=True)
  28.                     ]
  29.                 }
  30.                 # Guardar los resultados en la base de datos
  31.                 result_summary = ";".join(image_urls['urls'])
  32.                 new_analysis = ChatAnalysisResults(
  33.                     chat_name=filename,
  34.                     result_summary=result_summary
  35.                 )
  36.                 new_analysis.save()
  37.                 return jsonify(image_urls), 200
  38.             abort(400, description="File type not allowed")
  39.         # Captura el error y devuelve un mensaje serializable
  40.         except Exception as e:
  41.             return jsonify({"error": str(e)}), 500
复制代码
And here is the React component that handle the upload of the document (I am not very good at react):
这是处理文档上传的React组件(我对React不是很善于):
  1. import { useState } from 'react'
  2. import PropTypes from 'prop-types'
  3. import axios from 'axios'
  4. import '../App.css'
  5. function UploadForm({ setImages }) {
  6.     const [file, setFile] = useState(null);
  7.     const [response, setResponse] = useState('');
  8.     const [loading, setLoading] = useState(false);
  9.     const handleFileChange = (event) => {
  10.         setFile(event.target.files[0]);
  11.     };
  12.     const handleUpload = async () => {
  13.         if (!file) {
  14.             alert("Please select a chat file to upload.");
  15.             return;
  16.         }
  17.         const formData = new FormData()
  18.         formData.append('file', file) // Cambiado de 'chat_file' a 'file'
  19.         setLoading(true) // Inicia la animación de carga
  20.         setImages([])   // Limpia los resultados anteriores
  21.         setResponse('') // Opcional: limpia el mensaje de respuesta
  22.         console.log('Loading started');
  23.         try {
  24.             const response = await axios.post('http://127.0.0.1:8080/analysis/upload', formData, {
  25.                 headers: {
  26.                     'Content-Type': 'multipart/form-data'
  27.                 }
  28.             });
  29.             console.log('Response data:', response.data);
  30.             setImages(response.data.urls);
  31.             setResponse('Chat file analyzed successfully');
  32.         } catch (error) {
  33.             console.error('Error uploading the file:', error);
  34.             setResponse('Error uploading the file: ' + (error.response ? error.response.data.error : error.message));
  35.         } finally {
  36.             setLoading(false); // Detiene la animación de carga independientemente del resultado
  37.             console.log('Loading finished');
  38.         }
  39.     }
  40.     return (
  41.         <div className="upload-form">
  42.             <input type="file" onChange={handleFileChange} accept=".txt" />
  43.             <button onClick={handleUpload}>
  44.                 {loading ? 'Analyzing' : 'Analyze Chat'}
  45.             </button>
  46.             {response && <p>{response}</p>}
  47.             {loading && (
  48.             <div className='loading'>
  49.                 <div className='spinner'></div>
  50.             </div>
  51.             )}
  52.         </div>
  53.     )
  54. }
  55. UploadForm.propTypes = {
  56.     setImages: PropTypes.func.isRequired,
  57. }
  58. export default UploadForm
复制代码
And this is the error that I am getting in the console:
这是我在控制台中遇到的错误信息:

Also the error that I can see on the VSCode Terminal is the following:
同时,我在VSCode终端中看到的错误如下:
  1.   File "/opt/anaconda3/lib/python3.11/json/encoder.py", line 180, in default
  2.     raise TypeError(f'Object of type {o.__class__.__name__} '
  3. TypeError: Object of type Response is not JSON serializable
复制代码
All the API endpoints so far work correctly except for this one, I have been stuck with this problem for a week and I could use some help. If you need more info or want to see more parts/scripts of the project feel free to ask
到目前为止,所有的API端点都工作正常,除了这一个。我已经被这个问题困扰了一个星期,希望能得到一些资助。如果你需要更多信息大概想检察项目的其他部门/脚本,请随时告诉我



问题解决:

I can see there is a CORS policy error in your code. It arises because you are working on two different URLs, one for backend and one for frontend, and to resolve it you have to do changes in your flask code. Install flask_cors package and than import modules from it;
我看到你的代码中出现了CORS计谋错误。这是因为你正在利用两个不同的URL,一个用于后端,一个用于前端。为了解决这个问题,你需要在你的Flask代码中做一些更改。起首,你需要安装flask_cors包,然后从它里面导入模块;
  1. from flask_cors import cross_origin  #for specific route
  2. from flask_cors import CORS  #for whole app
复制代码
after importing
导入之后
  1. analysis_ns = Flask(__name__)  #you might have done this in beginning your code
  2. CORS(analysis_ns)  #for enabling CORS in whole app, define it at the beginning of your code
  3. #rest of your code
  4. @analysis_ns.route('/upload', methods=["POST", "GET"])
  5. @cross_origin  #for enabling CORS in specific route
  6. #rest of your code
复制代码
This might help to resolve the error. I had the CORS policy issue during my internship where I was working with same technology, that is, Flask and React.
这可能有助于解决错误。在我练习期间,我也在利用雷同的技术(即Flask和React)时遇到了CORS计谋问题。





免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

乌市泽哥

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表