まずはサンプルを見てください。
sample.py
1import json 2import falcon 3import MySQLdb 4from MySQLdb.cursors import DictCursor 5 6print("hello response code") 7 8class CORSMiddleware: 9 def process_request(self, req, resp): 10 resp.set_header('Access-Control-Allow-Origin', '*') 11 12class PostResource(object): 13 14 # postされた時の動作 15 def on_post(self, req, res): 16 17 body = req.stream.read() 18 data = json.loads(body) 19 20 # パラメーターの取得 21 name = data['name'] 22 id = data['id'] 23 24 connection = MySQLdb.connect( 25 host='localhost', 26 port=3306, 27 user='root', 28 passwd='password', 29 db='sample', 30 charset='utf8', 31 cursorclass=MySQLdb.cursors.DictCursor 32 ) 33 cursor = connection.cursor() 34 sql = "select * from business_term" 35 36 cursor.execute(sql) 37 data = cursor.fetchall() 38 39 cursor.close() 40 connection.commit() 41 connection.close() 42 43 res.status = falcon.HTTP_200 44 res.body = json.dumps(data) 45 print(res.body) 46 print("取得完了") 47 48app = falcon.API(middleware=[CORSMiddleware()]) 49app.add_route("/", PostResource()) 50 51 52if __name__ == "__main__": 53 from wsgiref import simple_server 54 httpd = simple_server.make_server("0.0.0.0", 8000, app) 55 httpd.serve_forever() 56 57
Python側のres.bodyはしっかりとJSON形式になっています。
test.js
1var myPost = function(){ 2 3 const method = 'POST'; 4 //送信先を指定 5 const url = 'http://0.0.0.0:8000' 6 const headers = { 7 'Content-Type': 'application/x-www-form-urlencoded' 8 }; 9 // 送信データを変換 10 var min = 0 ; 11 var max = 10 ; 12 var random = Math.floor( Math.random() * (max + 1 - min) ) + min ; 13 14 var name = Math.random().toString(36).slice(-8); 15 16 const body = JSON.stringify({"name" : name, "id": random}) 17 18 const options = { 19 method, 20 headers, 21 mode: 'cors', 22 body 23 } 24 fetch(url, options) 25 .then(res => { 26 //成功時の処理 27 console.log("success") 28 console.log(res) 29 window.location.reload(); 30 }) 31 .catch(err => { 32 //エラー時の処理 33 console.log("false") 34 console.error 35 }) 36 return false; 37 }
JSコンソール
1Response {type: "cors", url: "http://0.0.0.0:8000", redirected: false, status: 200, ok: true, …} 2body:(...) bodyUsed:false headers:Headers {} ok:true redirected:false status:200 statusText:"OK" type:"cors" url:"http://0.0.0.0:8000" __proto__:Response
問題として、Javascript側でのfetch成功時にresの中身を出力してみるのですが、bodyの中身がカラになってしまい、JSON取得が失敗となってしまいます。
何が悪いのでしょうか?
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。