Firebase Hostingにデプロイしたページから、Cloud RunにデプロイしたPythonプログラムに画像をPOSTし、確認のため画像をreturnしたいのですが、『CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.』とエラーが出てしまいます。
こちらのサイトを参考に、サンプル通りのコードでFirebase hostingとCloud Runの連携を行うことはできました。適当な文字列なども、returnすることができますがrequest.files['image']をreturnすると上記のエラーが発生します。
以下、ソースコードです。
他に必要な情報があればお願いします。
Vue.js
1<template> 2 <dev> 3 <form enctype="multipart/form-data" @submit.prevent="postImage" method="POST"> 4 <input type="file" name="image" accept="image/png, image/jpeg, image/jpg" @change="uploadImage" ref="image"> 5 <button type="submit">submit</button> 6 </form> 7 <img :src="url" width="50%"> 8 </dev> 9</template> 10 11<script> 12import Vue from "vue"; 13import axios from "axios"; 14export default Vue.extend({ 15 data(){ 16 return{ 17 url:null, 18 result: '', 19 } 20 }, 21 methods:{ 22 // 画像プレビュー 23 uploadImage:function(){ 24 this.url = URL.createObjectURL(this.$refs.image.files[0]); 25 }, 26 // 画像POST 27 async postImage() { 28 var params = new FormData() 29 params.append('image', this.result) 30 await axios.post( 31 "CouldRunのURL" , params 32 ) 33 .then(function (response) { 34 console.log(response) 35 }) 36 }, 37 } 38}); 39</script>
Python
1from flask import Flask, request 2from flask_cors import CORS 3 4app = Flask(__name__) 5CORS(app, supports_credentials=True) 6 7@app.after_request 8def after_request(response): 9 response.headers.add('Access-Control-Allow-Origin', '*') 10 response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') 11 response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') 12 return response 13 14@app.route('/', methods=['POST']) 15def result(): 16 return request.files['image'] 17 18if __name__ == '__main__': 19 app.run(debug=True, host='0.0.0.0', port=8080)
あなたの回答
tips
プレビュー