3 ms·
For the benefit of others wondering how it should be done instead: it’s best to use a proper type that will do the encoding, instead of passing a raw body. Sure
by chrismorgan 4y ago
For the benefit of others wondering how it should be done instead: it’s best to use a proper type that will do the encoding, instead of passing a raw body. Sure, you can perform the encoding yourself (e.g. `text=${encodeURIComponent(text)}`) and pass a raw body, but as things scale that’s much more error-prone; it’s better to let types do the lifting from the start (kinda like lifting heavy things by squatting rather than bending at the waist).
For application/x-www-form-urlencoded as shown, that’d be using URLSearchParams:
fetch("https://text-processing.com/api/sentiment", {
method: "POST",
body: new URLSearchParams({ text }),
})
If you wanted multipart/form-data instead (which I expect the API to support), you’d use FormData, which sadly can’t take a record in its constructor:
const body = new FormData();
body.append("text", text);
fetch("https://text-processing.com/api/sentiment", { method: "POST", body })
Note that in each case the content-type header is now superfluous: the former will give you "application/x-www-form-urlencoded;charset=UTF-8" (which is all the better for specifying the charset) and the latter a "multipart/form-data; boundary=…" string. (Spec source: https://fetch.spec.whatwg.org/#concept-bodyinit-extract https://fetch.spec.whatwg.org/#concept-bodyinit-extract.)
As a fun additional aside, you’ve made a tiny error in your transcription: the URL was actually surrounded in backticks (a template literal), not single quotation marks. Given the absence of a tag or placeholders (which would justify a template literal) and the use of double-quoted strings elsewhere, both of these would be curious choices that a style linter would be very likely to complain about. So yeah, just another small point where it’s generating weird code.