farrow-js/farrow

Question(http): Can I describe form data or x-www-form-urlencoded data? Or any way to support it?

tqma113 opened this issue · 5 comments

like this:

form data

const data = new URLSearchParams();
for (const pair of new FormData(formElement)) {
    data.append(pair[0], pair[1]);
}

fetch(url, {
    method: 'post',
    body: data,
})
.then();

or

x-www-form-urlencoded data

var details = {
    'userName': 'test@gmail.com',
    'password': 'Password!',
    'grant_type': 'password'
};

var formBody = [];
for (var property in details) {
  var encodedKey = encodeURIComponent(property);
  var encodedValue = encodeURIComponent(details[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

fetch('https://example.com/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  body: formBody
})

farrow-http use co-body internally for parsing req.body, form-data or urlencoded are supported.

See the code in farrow-http/src/util.ts

Oh, I see. But the form data maybe not the json-like data.

If I want to upload file like this:

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})

How should I describe it with router.match?

We can use Unknown to get the raw body and validate it by hand.

import { Unknown } from 'farrow-schema'
http.post('/avatars', {
  body: Unknown
}).use(request => {
   const body = getFormData(request.body)
}) 

file文件上传怎么搞呀

file文件上传怎么搞呀

@simonyouth 建议实用 farrow-expressfarrow-koa 适配器来用 farrow,这样上传文件部分,可以沿用 express/koa 里的中间件