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

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

Closed
tqma113 opened this issue Aug 24, 2021 · 5 comments

Comments

@tqma113
Copy link
Collaborator

tqma113 commented Aug 24, 2021

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
})
@Lucifier129
Copy link
Collaborator

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

@tqma113
Copy link
Collaborator Author

tqma113 commented Aug 24, 2021

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?

@Lucifier129
Copy link
Collaborator

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)
}) 

@tqma113 tqma113 closed this as completed Aug 24, 2021
@simonyouth
Copy link

file文件上传怎么搞呀

@Lucifier129
Copy link
Collaborator

file文件上传怎么搞呀

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants