Fixes #7162: Ensure BASE_PATH is only included in API calls once

This commit is contained in:
thatmattlove 2021-09-03 16:28:38 -07:00
parent acb24489d1
commit 70cd0969e4
12 changed files with 12 additions and 6 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,5 +1,5 @@
import { createToast } from './bs';
import { getElements, apiPatch, buildUrl, hasError, getSelectedOptions } from './util';
import { getElements, apiPatch, hasError, getSelectedOptions } from './util';
/**
* Mark each option element in the selected columns element as 'selected' so they are submitted to
@ -54,8 +54,7 @@ function removeColumns(event: Event): void {
* Submit form configuration to the NetBox API.
*/
async function submitFormConfig(formConfig: Dict<Dict>): Promise<APIResponse<APIUserConfig>> {
const url = buildUrl('/api/users/config/');
return await apiPatch<APIUserConfig>(url, formConfig);
return await apiPatch<APIUserConfig>('/api/users/config/', formConfig);
}
/**

View File

@ -157,16 +157,21 @@ function queryParamsToObject(params: string): Record<string, Stringifiable[]> {
*
* @param path Relative path _after_ (excluding) the `BASE_PATH`.
*/
export function buildUrl(destination: string): string {
function buildUrl(destination: string): string {
// Separate the path from any URL search params.
const [pathname, search] = destination.split(/(?=\?)/g);
// If the `origin` exists in the API path (as in the case of paginated responses), remove it.
const origin = new RegExp(window.location.origin, 'g');
const path = pathname.replaceAll(origin, '');
let path = pathname.replaceAll(origin, '');
const basePath = getBasePath();
// If the `BASE_PATH` already exists in the URL, remove it.
if (basePath !== '' && path.includes(basePath)) {
path = path.replaceAll(basePath, '');
}
// Combine `BASE_PATH` with this request's path, removing _all_ slashes.
let combined = [...basePath.split('/'), ...path.split('/')].filter(p => p);
@ -185,7 +190,7 @@ export function buildUrl(destination: string): string {
}
export async function apiRequest<R extends Dict, D extends ReqData = undefined>(
url: string,
path: string,
method: Method,
data?: D,
): Promise<APIResponse<R>> {
@ -198,6 +203,8 @@ export async function apiRequest<R extends Dict, D extends ReqData = undefined>(
headers.set('content-type', 'application/json');
}
const url = buildUrl(path);
const res = await fetch(url, { method, body, headers, credentials: 'same-origin' });
const contentType = res.headers.get('Content-Type');
if (typeof contentType === 'string' && contentType.includes('text')) {