Skip to content
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

hook.server.ts does not work for a preflight request #8963

Closed
taishi55 opened this issue Feb 9, 2023 · 5 comments
Closed

hook.server.ts does not work for a preflight request #8963

taishi55 opened this issue Feb 9, 2023 · 5 comments

Comments

@taishi55
Copy link

taishi55 commented Feb 9, 2023

Describe the bug

Error message on client side: Access to fetch at 'https://myapp-vercel.app/api/search' from origin 'https://chat.openai.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Reproduction

hooks.server.ts (Deployed to Vercel.)

import type { Handle } from '@sveltejs/kit';

export const handle: Handle = async ({ event, resolve }) => {
	const response = await resolve(event);
	if (event.url.pathname.includes('/api')) {
		// https://chat.openai.com
		response.headers.set('Access-Control-Allow-Origin', 'https://example.com');
		response.headers.set('Access-Control-Allow-Methods', 'GET,OPTIONS,POST');
		response.headers.set('Access-Control-Max-Age', '86400');
	}
	return response;
};

+server.ts (Deployed to Vercel.)

export const POST: RequestHandler = async ({ request }) => {
	const { query, time, instruction } = await request.json();
	try {
	const data: string = await getTranscript(query);
	return new Response(data, { status: 200 });
	} catch {
	return new Response("" { status: 500 });
	}
}

Fetching from the origin (https://example.com) on client side:

const submit = async () => {
		const headers = new Headers({
			Origin: 'https://example.com',
			'content-type': 'application/json'
		});
		try {
			const response = await fetch('https://myapp.com/api/search', {
				method: 'POST',
				body: JSON.stringify({
					query,
					time,
					instruction
				}),
				headers
			});

			result = await response.text();
		} catch (error) {
			// showErrorMessage(error);
			console.log(error);
		}
	};

Logs

I've been searching this issue a lot. There are some people who experience the same isssue.
https://www.reddit.com/r/sveltejs/comments/u4wepc/solving_cors_problems_when_using_sveltekitvercel/

https://discord.com/channels/457912077277855764/1023340103071965194/threads/1051823361933705216

System Info

System:
    OS: macOS 12.4
    CPU: (8) arm64 Apple M1
    Memory: 103.13 MB / 8.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.15.0 - /usr/local/bin/node
    npm: 8.19.2 - /usr/local/bin/npm
  Browsers:
    Brave Browser: 109.1.47.186
    Safari: 15.5
  npmPackages:
    @sveltejs/adapter-auto: ^2.0.0 => 2.0.0 
    @sveltejs/kit: ^1.5.0 => 1.5.0 
    svelte: ^3.54.0 => 3.55.1 
    vite: ^4.0.0 => 4.1.1

Severity

annoyance

Additional Information

No response

@Conduitry
Copy link
Member

Can you tell what response is being returned by the preflight response, if not a successful response?

Do you need to return Access-Control-Allow-Headers?

@taishi55
Copy link
Author

taishi55 commented Feb 9, 2023

@Conduitry
The unsuccessful response is a empty string. return new Response("" { status: 500 });

The error message is below.

Access to fetch at 'https://myapp/api/search' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Do you need to return Access-Control-Allow-Headers?

Yes need to return to the allowed origin url.

@taishi55
Copy link
Author

taishi55 commented Feb 9, 2023

@Conduitry

I added Access-Control-Allow-Headers, but still not working. getting same error message...

hooks.server.ts

import type { Handle } from '@sveltejs/kit';

export const handle: Handle = async ({ event, resolve }) => {
	const response = await resolve(event);
	if (event.url.pathname.includes('/api')) {
		// https://chat.openai.com
		response.headers.set('Access-Control-Allow-Origin', 'https://example.com');
		response.headers.set('Access-Control-Allow-Methods', 'GET,OPTIONS,POST');
		response.headers.set('Access-Control-Allow-Headers', '*');
		response.headers.set('Access-Control-Max-Age', '86400');
	}
	return response;
};

@taishi55
Copy link
Author

taishi55 commented Feb 9, 2023

The problem was #5193 (comment)

@taishi55
Copy link
Author

taishi55 commented Feb 9, 2023

Look #5193 (comment) to solve the issue.

@eltigerchino eltigerchino closed this as not planned Won't fix, can't repro, duplicate, stale Feb 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants