Django + svelte + ngrok:已阻止跨源请求:同源策略不允许阅读远程

m1m5dgzv  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(163)

我正在Django + Slvelte平台上工作,他们中的每一个都托管在本地服务器上,本地主机工作正常,没有错误,当我试图使用ngrok隧道,以便能够让我的朋友来测试平台,我得到了这个错误Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://452c-102-159-49-36.ngrok-free.app/api/courses/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200
这是来自svelte组件的API调用:

async function fetchCourseOptions() {
    try {
      const response = await fetch(
        "https://452c-102-159-49-36.ngrok-free.app/api/courses/"
      );
      const data = await response.json();
      courseSelected = true;
      return data.courses;
    } catch (error) {
      console.error("Error while fetching course options:", error);
      return [];
    }
  }

字符串
这是ngrok中的隧道配置

tunnels:
  django:
    proto: http
    addr: 127.0.0.1:8000
  svelte:
    proto: http
    addr: 5173


这些是域:

Forwarding                    https://25fc-102-159-49-36.ngrok-free.app -> http://localhost:5173                                                       Forwarding                    https://452c-102-159-49-36.ngrok-free.app -> http://127.0.0.1:8000


我试着在Django settings.py中将地址添加到cors允许的源地址和允许的主机地址中

ALLOWED_HOSTS = ["452c-102-159-49-36.ngrok-free.app", "localhost"]

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "profikapp.apps.ProfikappConfig",
    "smart_selects",
    "api.apps.ApiConfig",
    "corsheaders",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "corsheaders.middleware.CorsMiddleware",
]

ROOT_URLCONF = "profik.urls"

CORS_ALLOWED_ORIGINS = [
    "http://localhost:5173",
    "https://25fc-102-159-49-36.ngrok-free.app",
    "https://452c-102-159-49-36.ngrok-free.app",
    "https://5ab8-102-159-49-36.ngrok-free.app",
]


但它不起作用,它仍然给我错误,我不明白为什么。我至少需要帮助来找出错误的原因

gkl3eglg

gkl3eglg1#

您可以尝试允许所有,然后查看请求的来源:
要执行此操作,请执行以下操作:

#settings.py

CORS_ORIGIN_ALLOW_ALL = True

#add this to your function, it'll print the source of the request
print(request.META['HTTP_REFERER'])

字符串
请勿在产品中使用

相关问题