diff --git a/README.md b/README.md index 121ed97..444744a 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,23 @@ async myMethod () { } ``` +#### Request body + +Instead of stringify the body of a request which the content type is `application/json`, you can just pass the javascript object as the body of the request and Request.JS will stringify it for you. + +```js +import { post } from '@rails/request.js' + +... + +async myMethod () { + const response = await post('localhost:3000/my_endpoint', { body: { name: 'Request.JS' } }) + if (response.ok) { + ... + } +} +``` + #### Turbo Streams diff --git a/src/fetch_request.js b/src/fetch_request.js index 3d0684c..08a0d80 100644 --- a/src/fetch_request.js +++ b/src/fetch_request.js @@ -24,7 +24,10 @@ export class FetchRequest { return Promise.reject(window.location.href = response.authenticationURL) } - if (response.ok && response.isTurboStream) { response.renderTurboStream() } + if (response.ok && response.isTurboStream) { + response.renderTurboStream() + } + return response } @@ -38,7 +41,7 @@ export class FetchRequest { return { method: this.method.toUpperCase(), headers: this.headers, - body: this.body, + body: this.formattedBody, signal: this.signal, credentials: 'same-origin', redirect: 'follow' @@ -101,4 +104,15 @@ export class FetchRequest { get additionalHeaders () { return this.options.headers || {} } + + get formattedBody () { + const bodyIsAString = Object.prototype.toString.call(this.body) === '[object String]' + const contentTypeIsJson = this.headers['Content-Type'] === 'application/json' + + if (contentTypeIsJson && !bodyIsAString) { + return JSON.stringify(this.body) + } + + return this.body + } }