Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Koa 接受 Fetch Post数据 #7

Open
HAAAAADION opened this issue Nov 30, 2016 · 0 comments
Open

Koa 接受 Fetch Post数据 #7

HAAAAADION opened this issue Nov 30, 2016 · 0 comments

Comments

@HAAAAADION
Copy link
Owner

HAAAAADION commented Nov 30, 2016

环境使用Koa v3版本 + node.js
Koa要接收POST的数据可以使用中间件koa-bodyparser
其他body库支持koa版本以及介绍

//设置
import bodyParser from 'koa-bodyparser';
app.use(bodyParser());

//调用
router.post('/indie/song/1', (ctx, next) => {
    console.log(ctx.request.body);
});

Jquery$.ajax()直接设置data参数即可.

Fetch参数可以设置body参数

fetch(url, {
    method: "post",
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: 'title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3'
})
    .then(e => e.json())
    .then(s => {
        console.log(s);
    });
注意!使用Fetch传参时需要设置headers,否则服务端无法接收

application/x-www-form-urlencoded

浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。提交的数据按照 key1=val1&key2=val2 的方式进行编码,key 和 val 都进行了 URL 转码。

POST http://www.123.com HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=utf-8

title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3

multipart/form-data

使用表单上传文件时,必须让 form 的 enctyped 等于这个值, 上传图片时,我们经常会看到下面这样

POST http://www.example.com HTTP/1.1
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA

------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="text"

title
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="file"; filename="chrome.png"
Content-Type: image/png

PNG ... content of chrome.png ...
------WebKitFormBoundaryrGKCBY7qhFd3TrwA--

application/json

把它作为请求头,用来告诉服务端消息主体是序列化后的 JSON 字符串。但也有些服务端语言还没有支持这种方式,例如 php 就无法通过 $_POST 对象从上面的请求中获得内容。这时候,需要自己动手处理下:在请求头中 Content-Type 为 application/json 时,从 php://input 里获得原始输入流,再 json_decode 成对象。

`{"static": "true"}`

参考文章:

  1. Fetch POST接收不到数据,注意content-type的设置
  2. MDN fetch文档
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant