Deep learning 2022-04-04 16:53 采纳率: 69.2%
浏览 29

被CORS政策屏蔽怎么办?

img


我后端用的是python+flask


from flask import Flask
import json
# from httpx import request
import pymysql
from flask import request
from flask_cors import CORS


app = Flask(__name__)
# CORS(app, resources=r'/*')    
# 注册CORS, "/*" 允许访问所有api

# 连接数据库
db = pymysql.connect(host='localhost',
                     user='root',
                     password='root',
                     database='demo',
                     charset='utf8mb4',
                     cursorclass=pymysql.cursors.DictCursor)


# 默认是get
@app.route("/")
def init():
    cursor = db.cursor()  # 使用cursor()创建游标对象cursor
    try:
        sqlview = 3
        # SQL插入语句
        sql = "SELECT * FROM blog WHERE views = %s" % (sqlview)

        cursor.execute(sql)

        # 获取所有记录列表list
        results = cursor.fetchall()
        print(results)
        db.commit()
        print("代码执行完毕")
    except pymysql.Error as err:
        print(err)
    finally:
        cursor.close()
        # db.close()
    # 返回数据(json格式)
    return json.dumps(results, ensure_ascii=False, default=str)


# 生成字幕
# methods=['GET', 'POST']表示只接受GET与POST请求
@app.route("/pyapi/postAudioSubtitles", methods=['POST', 'GET'])
def post_Audio_Subtitles():
    if request.method == 'GET':
        return 'GET postAudioSubtitles'
    elif request.method == 'POST':
        # 获取前端传递过来json,获取key为videoPath的值
        print("001")
        print(request.json)
        # videoPath = request.json['videoPath']
        # print(videoPath)
        return "ok"
        # return videoPath
        # return make_response('VideoSummary', headers)
    

# 生成视频摘要
@app.route("/pyapi/postVideoSummary", methods=['POST', 'GET'])
def post_Video_Summary():
    if request.method == 'GET':
        return 'GET postVideoSummary'
    elif request.method == 'POST':
        # 获取前端传递过来json,获取key为content的值
        print(request.json)
        videoPath = request.json['videoPath']
        print(videoPath)
        return videoPath

if __name__ == '__main__':
    CORS(app, resources=r'/*')
    # 设置调试模式,生产模式的时候要关掉debug
    app.run(host='127.0.0.1', port=5001, debug=True)

我前端用的是vue


```html

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <el-button type="primary" @click="showSubtitle">显示字幕</el-button>
    <el-button type="primary" plain @click="showVideoSummary">打开摘要</el-button>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    showSubtitle () {
      const path = 'http://127.0.0.1:5001/pyapi/postAudioSubtitles'
      axios.post(path, {
        videoPath: 'jiayo1'
      })
        .then(function (response) {
          console.log('显示字幕:获取返回数据')
          console.log(response.data)
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    showVideoSummary () {
      axios.post('http://127.0.0.1:5001/pyapi/postVideoSummary', {
        videoPath: 'hjsafajbf'
      })
        .then(function (response) {
          console.log('显示摘要:获取返回数据')
          console.log(response.data)
        })
        .catch(function (error) {
          console.log(error)
        })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>


```

  • 写回答

1条回答 默认 最新

  • GavinHaydy 2022-04-07 23:21
    关注
    # 在11行加上如下代码
    CORS(app, supports_credentials=True)
    
    评论

报告相同问题?

问题事件

  • 创建了问题 4月4日

悬赏问题

  • ¥30 为什么会失败呢,该如何调整
  • ¥50 如何在不能联网影子模式下的电脑解决usb锁
  • ¥20 服务器redhat5.8网络问题
  • ¥15 如何利用c++ MFC绘制复杂网络多层图
  • ¥20 要做柴油机燃烧室优化 需要保持压缩比不变 请问怎么用AVL fire ESE软件里面的 compensation volume 来使用补偿体积来保持压缩比不变
  • ¥15 python螺旋图像
  • ¥15 算能的sail库的运用
  • ¥15 'Content-Type': 'application/x-www-form-urlencoded' 请教 这种post请求参数,该如何填写??重点是下面那个冒号啊
  • ¥15 找代写python里的jango设计在线书店
  • ¥15 请教如何关于Msg文件解析