V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
miniyao
V2EX  ›  Python

flask 怎么接收从前端直接 POST 传过来的字符串 xhr.send('string') ?

  •  
  •   miniyao · 2019-11-22 15:02:31 +08:00 · 3814 次点击
    这是一个创建于 1588 天前的主题,其中的信息可能已经有所发展或是发生改变。

    看了 MDN 的规范,前端可用直接异步 POST 字符串到后端 // xhr.send('string');

    var xhr = new XMLHttpRequest();
    xhr.open("POST", '/server', true);
    
    //发送合适的请求头信息
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
    xhr.onload = function () { 
        // 请求结束后,在此处写处理代码 
    };
    xhr.send("foo=bar&lorem=ipsum"); 
    // xhr.send('string'); 
    // xhr.send(new Blob()); 
    // xhr.send(new Int8Array()); 
    // xhr.send({ form: 'data' }); 
    // xhr.send(document);
    
    

    这种纯字符串,不是字典、也不是 json,后端用 flask 的 request 怎么接收呢?

    4 条回复    2019-11-22 17:09:13 +08:00
    mink
        1
    mink  
       2019-11-22 15:17:44 +08:00
    request.data , 可以使用 dir(request) 之后把所有关于数据获取的全部打印一遍就知道了
    miniyao
        2
    miniyao  
    OP
       2019-11-22 15:47:56 +08:00
    @mink 找了下,差不多,貌似是 request.get_data()
    locoz
        3
    locoz  
       2019-11-22 16:25:33 +08:00
    就是纯字符串的 body 嘛,直接读 data 就行。这种情况我一般是本地用 pycharm 起个 debug 模式,然后断点断下来,再发个请求过来,然后就能直接看是哪一项了,文档都不用看。
    Latin
        4
    Latin  
       2019-11-22 17:09:13 +08:00
    这是标准的 formdata 直接 dict(request.form)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3329 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:44 · PVG 21:44 · LAX 06:44 · JFK 09:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.