Vue.js 查询 Flask 结果在 PC Chrome 上显示,但在 Android Chrome、Opera、Edge 上不显示,而在 Firefox 上都能正常工作

2 投票
1 回答
31 浏览
提问于 2025-04-14 15:50

我正在做一个基于Vue.js的网站,想要从前端发送查询到我的Flask后端,然后搜索一些docx文档,最后把一些文本和图片作为搜索结果显示在屏幕上。奇怪的是,我的代码在PC上的Chrome浏览器上能正常工作,但在安卓的Chrome浏览器上却不行,不过在Firefox上两个都能运行。顺便说一下,我是在开发模式下进行的。

这是我用来输入查询的search.vue文件。

<template>
  <div>
    <ul v-if="searchResults.length">
      <li v-for="(result, index) in searchResults" :key="`result-${index}`">
        {{ result.filename }}
        <p v-for="(text, textIndex) in result.text" :key="`text-${index}-${textIndex}`">{{ text }}</p>
        <img 
          v-for="(image, imageIndex) in result.images" 
          :src="`/static/extracted_images/${image}`" 
          :alt="`Image ${imageIndex}`"
          :key="`image-${index}-${imageIndex}`" >
      </li>
    </ul>
  </div>
</template>


<script>
import axios from 'axios';

export default {
  data() {
    return {
      searchResults: [],
    };
  },
  watch: {
    '$route.query.q': {
      immediate: true,
      handler(newQuery) {
        this.query = newQuery || '';
        this.fetchSearchResults();
      },
    },
  },
  methods: {
    fetchSearchResults() {
  axios.get(`${process.env.VUE_APP_BACKEND_URL}/api/search`, { params: { query: this.query } })
    .then(response => {
      this.searchResults = response.data;
    })
    .catch(error => {
      console.error('Error fetching search results:', error);
    });
}
  }
};
</script>

这是我的后端Flask代码。

@app.route('/api/search')
def search():
    search_query = request.args.get('query', '')
    directory = r"C:/Users/ID/Desktop/App/uploads"
    search_results = search_documents(directory, search_query)
    return jsonify(search_results)

这个是处理搜索文档的函数。

def search_documents(directory, id_str):
    results = []
    for filename in os.listdir(directory):
        if filename.endswith(".docx"):
            doc_path = os.path.join(directory, filename)
            extracted_data = extract_content(doc_path, id_str)

            # seperate text and images
            text = [item['content'] for item in extracted_data if item['type'] == 'text']
            images = [item['content'] for item in extracted_data if item['type'] == 'image']

            if text or images:  
                results.append({
                    'filename': filename,
                    'text': text,
                    'images': images
                })

    return results


def extract_content(doc_path, id_str):
    doc = Document(doc_path)
    extracted_data = []

    image_directory = r"C:/Users/ID/Desktop/vue.jsExample/Vue-3/MaidsPost/public/static/extracted_images"
    os.makedirs(image_directory, exist_ok=True)

    is_collecting = False

    #aquire texts
    for para in doc.paragraphs:
        text = para.text.strip()

        if id_str in text:
            is_collecting = True
        elif "extracted_time: " in text and is_collecting:
            is_collecting = False

        if is_collecting:
            extracted_data.append({'type': 'text', 'content': text})
        
        # aquire images
        if is_collecting:
            for run in para.runs:
                print(para.runs)
                for shape in run.element.iter():
                    if shape.tag.endswith('blip'):
                        image_rid = shape.attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed']
                        image_part = doc.part.related_parts[image_rid]
                        image_filename = f"extracted_image_{uuid.uuid4()}.png"
                        image_path = os.path.join(image_directory, image_filename)

                        with open(image_path, 'wb') as f:
                            f.write(image_part.blob)
                            extracted_data.append({'type': 'image', 'content': image_filename})
    
    return extracted_data

我在安卓上清除了浏览数据。

我为不同的屏幕尺寸设计了不同的CSS样式。

我尝试重写extract_content()函数,看看不同的方法是否能解决问题。

还尝试重写search.vue中的脚本。

后端确实收到了请求,所以我试着打印出一些变量,发现问题似乎出在extract_content()中,图片没有被提取出来。不过我尝试了不同的方法来获取图片,但都没有成功。

1 个回答

0
text = para.text.strip().lower()
id_str = id_str.lower()

结果发现,在安卓的Chrome浏览器和其他一些浏览器中,大小写是敏感的。而在Windows的Chrome浏览器上则不是。所以我修改了这两行代码,得到了想要的结果。

撰写回答