Ad
Interface For Http Headers In The Fetch Method
I have a method that fires a fetch function. It also sets headers over which type I would like to have control.
// Request headers
let headers: HttpHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
// Checks if user have x-auth-token cookie
const token = getCookie(AUTH.COOKIE_NAME);
if (token !== null) {
headers = {
...headers,
[AUTH.API_TOKEN]: token
};
}
// Request body
const request = {
method,
headers,
body: JSON.stringify(body)
};
if (body || method.toUpperCase() === HttpMethod.GET) {
delete request.body;
}
I have also enum, which holds all allowed headers:
export enum HttpHeader {
ACCEPT = 'Accept',
CONTENT_TYPE = 'Content-Type',
X_AUTH_TOKEN = 'x-auth-token'
}
I already know that you can't specify enum as the expected index value in the ts interface. Can you give me another option to control http request headers? I saw the idea of using an array of objects, but I have the impression that it is a bit of a form over content.
Ad
Answer
You can use an enum to define a type that has all the enum values as keys using a mapped type (what you can't do is have an enum as an index parameter).
The predefined Record
and Partial
mapped types will do the job nicely:
type HttpHeaders = Partial<Record<HttpHeader, string>>
export enum HttpHeader {
ACCEPT = 'Accept',
CONTENT_TYPE = 'Content-Type',
X_AUTH_TOKEN = 'x-auth-token'
}
// Request headers
let headers: HttpHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
headers = {
...headers,
[HttpHeader.X_AUTH_TOKEN]: "token"
};
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad