eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule proposal: force `method: "POST"` on fetch calls with body

Open GauBen opened this issue 3 years ago • 7 comments

Description

I sometimes forget to add method: 'POST' to fetch calls

image

Fail

fetch('http://example.com', { body: '{}' })

Pass

fetch('http://example.com', { method: 'POST', body: '{}' })

Additional Info

No response

GauBen avatar Nov 22 '22 11:11 GauBen

Another thing related to fetch - disallow specifying method: 'GET' as it will be set by default

dimaMachina avatar Nov 22 '22 12:11 dimaMachina

Should not enforce POST, but forbid 'GET'(or omitted)/'HEAD'

fisker avatar Nov 22 '22 12:11 fisker

No HTTP method strictly forbids a body, and there are definitely examples of APIs that accept a body on GET, like elasticsearch.

silverwind avatar Nov 22 '22 20:11 silverwind

No HTTP method strictly forbids a body

The fetch spec forbid it,

If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.

https://fetch.spec.whatwg.org/#request-class

fisker avatar Nov 30 '22 01:11 fisker

Interesting, didn't know that. I guess some implemententations may opt to not implement that step, but for a general case, it seems good to have the rule for it then.

I do forsee that the spec may change in the future, similar to how initially a body on DELETE was forbidden by older RFCs, but newer specs now say it MAY have a body 😉. At least OpenAPI reverted their previous policy and they do allow body on GET,HEAD and DELETE.

silverwind avatar Nov 30 '22 07:11 silverwind

no-invalid-fetch-options?

fisker avatar May 08 '24 03:05 fisker

no-invalid-fetch-options

👍

sindresorhus avatar May 08 '24 07:05 sindresorhus