鍍金池/ 問答/Python/ 前后分離且跨域的Flask項(xiàng)目 中 POST application/x-www

前后分離且跨域的Flask項(xiàng)目 中 POST application/x-www-form-urlencoded 數(shù)據(jù)的怎么獲取

Flask 框架,項(xiàng)目是前后分離。 請(qǐng)求為fetch,后端post拿不到數(shù)據(jù);
具體癥狀:

1. get可以獲取,post請(qǐng)求發(fā)出后請(qǐng)求被掛起,頁面沒有響應(yīng);
2. 只要后端代碼出現(xiàn)request.form就會(huì)出現(xiàn)被掛起
3. 搜索網(wǎng)上和segmentfault的寫法,均無效;
4. 請(qǐng)求是
        POST
        Formdata
            username: 'aaa'
            password: '11221212' 
            
               

后端代碼

@app.route('/blog/login', methods=['post'])
def login():
        try:
                print(334,request.method, request.form.get('username'))
        except:
                print(11111)
        return '123'

錯(cuò)誤信息

Traceback (most recent call last):
  File "/Users/zhongwangsheng/Developer/PyProject/family/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 270, in run_wsgi
    execute(self.server.app)
  File "/Users/zhongwangsheng/Developer/PyProject/family/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 261, in execute
    write(data)
  File "/Users/zhongwangsheng/Developer/PyProject/family/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 236, in write
    self.send_header('Server', self.version_string())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/BaseHTTPServer.py", line 401, in send_header
    self.wfile.write("%s: %s\r\n" % (keyword, value))
IOError: [Errno 32] Broken pipe

以下為修改后的登錄代碼,還是一樣的錯(cuò)誤“請(qǐng)求被掛起,沒反應(yīng),約1分鐘后失敗error”

@app.route('/blog/login', methods=['post'])
def login():
        try:
                print(111, request.data)
                print(222, request.form)
        except:
                print(333)
        return 1234

以下是用fetch發(fā)送的請(qǐng)求信息

Request URL:http://localhost:8084/blog/login
Referrer Policy:no-referrer-when-downgrade
Provisional headers are shown
Authorization:
Content-Type:application/x-www-form-urlencoded
Origin:http://localhost:8084
Referer:http://localhost:8084/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36 OPR/51.0.2830.55 (Edition Baidu)

Form Data
    password:123456
    username:zws
回答
編輯回答
青裙

應(yīng)該不會(huì)是跨域問題的,假如跨域了,是到不了你的邏輯代碼的。
現(xiàn)在的信息判斷不出為什么,但是你可以嘗試把request.form替換成request.data試下

2017年7月31日 05:48
編輯回答
舊酒館

建議一步步進(jìn)行排查
先在login方法什么都不要寫,直接return一個(gè)值,驗(yàn)證一下你說的“只要后端代碼出現(xiàn)request.form就會(huì)出現(xiàn)被掛起”

2017年1月21日 20:23
編輯回答
尐飯團(tuán)

測(cè)試正常

>>> requests.post('http://127.0.0.1:5000/blog/login', data={'username':'hello'})
<Response [200]>
 * Running on http://127.0.0.1:5000/
(334, 'POST', u'hello')

如果其它地方正常,估計(jì)你沒有寫這個(gè)

from flask import request
2017年7月10日 19:33