Skip to content

Document request and response options #26

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

Merged
merged 1 commit into from
Jul 28, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ async myMethod () {
}
```

### responseKind

You can provide this option to specify which kind of response will be accepted. Default is `html`.

Options are `html`, `turbo-stream`, `json`.

### contentType

When provided this value will be sent in the `Content-Type` header. When not provided Request.JS will send nothing when the `body` of the request is `null` or an instance of `FormData`, when the `body` is an instance of a `File` then the type of the file will be sent and `application/json` will be sent if none of the prior conditions matches.

#### Turbo Streams

Expand All @@ -81,6 +90,8 @@ import { Turbo } from "@hotwired/turbo-rails"
window.Turbo = Turbo
```

Since [v7.0.0-beta.6](https://github.com/hotwired/turbo/releases/tag/v7.0.0-beta.6) Turbo sets `window.Turbo` automatically.

#### Request Interceptor

To authenticate fetch requests (eg. with Bearer token) you can use request interceptor. It allows pausing request invocation for fetching token and then adding it to headers:
Expand All @@ -99,6 +110,40 @@ RequestInterceptor.register(async (request) => {
RequestInterceptor.reset()
```

## Response

### statusCode

Returns the response status.

### ok

Returns true if the response was successful.

### unauthenticated

Returns true if the response has a `401` status code.

### authenticationURL

Returns the value contained in the `WWW-Authenticate` header.

### contentType

Returns the response content-type.

### html

Returns the html body, if the content type of the response isn't `html` then will be returned a rejected promise.

### json

Returns the json body, if the content type of the response isn't `json` then will be returned a rejected promise.

### headers

Returns the response headers.

# Known Issues

`FetchRequest` sets a `"X-Requested-With": "XmlHttpRequest"` header. If you have not upgraded to Turbo and still use `Turbolinks` in your Gemfile, this means
Expand Down