diff --git a/examples/ssr/src/api.ts b/examples/ssr/src/api.ts index 64dfe17d3..8a903b217 100644 --- a/examples/ssr/src/api.ts +++ b/examples/ssr/src/api.ts @@ -17,11 +17,12 @@ interface Cart { }>; } -const { MODE } = import.meta.env; -const origin = MODE === 'development' ? `http://127.0.0.1:3000` : `http://127.0.0.1:8085`; +function getOrigin(request: Request): string { + return new URL(request.url).origin.replace('localhost', '127.0.0.1'); +} -async function get(endpoint: string, cb: (response: Response) => Promise): Promise { - const response = await fetch(`${origin}${endpoint}`, { +async function get(incomingReq: Request, endpoint: string, cb: (response: Response) => Promise): Promise { + const response = await fetch(`${getOrigin(incomingReq)}${endpoint}`, { credentials: 'same-origin', }); if (!response.ok) { @@ -31,36 +32,36 @@ async function get(endpoint: string, cb: (response: Response) => Promise): return cb(response); } -export async function getProducts(): Promise { - return get('/api/products', async (response) => { +export async function getProducts(incomingReq: Request): Promise { + return get(incomingReq, '/api/products', async (response) => { const products: Product[] = await response.json(); return products; }); } -export async function getProduct(id: number): Promise { - return get(`/api/products/${id}`, async (response) => { +export async function getProduct(incomingReq: Request, id: number): Promise { + return get(incomingReq, `/api/products/${id}`, async (response) => { const product: Product = await response.json(); return product; }); } -export async function getUser(): Promise { - return get(`/api/user`, async (response) => { +export async function getUser(incomingReq: Request): Promise { + return get(incomingReq, `/api/user`, async (response) => { const user: User = await response.json(); return user; }); } -export async function getCart(): Promise { - return get(`/api/cart`, async (response) => { +export async function getCart(incomingReq: Request): Promise { + return get(incomingReq, `/api/cart`, async (response) => { const cart: Cart = await response.json(); return cart; }); } -export async function addToUserCart(id: number | string, name: string): Promise { - await fetch(`${origin}/api/cart`, { +export async function addToUserCart( id: number | string, name: string): Promise { + await fetch(`${location.origin}/api/cart`, { credentials: 'same-origin', method: 'POST', mode: 'no-cors', diff --git a/examples/ssr/src/components/Header.astro b/examples/ssr/src/components/Header.astro index c4d925a5f..426fb4be5 100644 --- a/examples/ssr/src/components/Header.astro +++ b/examples/ssr/src/components/Header.astro @@ -3,7 +3,7 @@ import TextDecorationSkip from './TextDecorationSkip.astro'; import Cart from './Cart.svelte'; import { getCart } from '../api'; -const cart = await getCart(); +const cart = await getCart(Astro.request); const cartCount = cart.items.reduce((sum, item) => sum + item.count, 0); ---