After login, modify global axios helper to include this token in all future requests
This commit is contained in:
parent
f182f16fe8
commit
3b30f11d0f
@ -1,6 +1,6 @@
|
|||||||
import { A, useNavigate } from "@solidjs/router";
|
import { A, useNavigate } from "@solidjs/router";
|
||||||
import { createSignal, onMount, Show } from "solid-js";
|
import { createSignal, onMount, Show } from "solid-js";
|
||||||
import { backend, UserInfo } from "../utils";
|
import { backend, set_auth_token, UserInfo } from "../utils";
|
||||||
import { Card } from "../components/Card";
|
import { Card } from "../components/Card";
|
||||||
import { AxiosError } from "axios";
|
import { AxiosError } from "axios";
|
||||||
|
|
||||||
@ -119,6 +119,7 @@ function UserRegistration(props: {setUserInfo: (u: UserInfo) => void}) {
|
|||||||
props.setUserInfo(response.data);
|
props.setUserInfo(response.data);
|
||||||
localStorage.setItem(userIdKey, response.data.UserId);
|
localStorage.setItem(userIdKey, response.data.UserId);
|
||||||
localStorage.setItem(usernameKey, response.data.Username);
|
localStorage.setItem(usernameKey, response.data.Username);
|
||||||
|
set_auth_token(response.data.UserId);
|
||||||
} catch (_e) {
|
} catch (_e) {
|
||||||
const e = _e as AxiosError<{error: string}>;
|
const e = _e as AxiosError<{error: string}>;
|
||||||
|
|
||||||
|
14
src/utils.ts
14
src/utils.ts
@ -1,9 +1,21 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
|
||||||
export const backend = axios.create({
|
export let backend = axios.create({
|
||||||
baseURL: `${import.meta.env.VITE_BACKEND_URL}/api`,
|
baseURL: `${import.meta.env.VITE_BACKEND_URL}/api`,
|
||||||
|
headers: {
|
||||||
|
"Authorization": `Bearer ${localStorage.getItem("UserId") ?? ""}`,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export function set_auth_token(token: string) {
|
||||||
|
backend = axios.create({
|
||||||
|
baseURL: `${import.meta.env.VITE_BACKEND_URL}/api`,
|
||||||
|
headers: {
|
||||||
|
"Authorization": `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export type UserInfo = {
|
export type UserInfo = {
|
||||||
UserId: string,
|
UserId: string,
|
||||||
Username: string,
|
Username: string,
|
||||||
|
Loading…
Reference in New Issue
Block a user