首页 > 解决方案 > Ktor 后端的 CORS 问题

问题描述

我正在创建一个全栈应用程序,后端在 Ktor (Kotlin) 中开发,前端在 React (TypeScript) 中开发。后端托管在 Heroku 上,而前端仍在开发中,因此我在本地运行它。

在使用 Postman 进行测试时,该 API 可操作并按预期工作。这是 Ktor 配置的摘录:

@Suppress("unused")
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {

    install(CORS) {
        anyHost()
    }

    install(StatusPages) {
        // Status pages configuration
    }

    install(ContentNegotiation) {
        jackson {
            enable(SerializationFeature.INDENT_OUTPUT)
            disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES)
        }
    }

    routing {
        // Declaration of routes
    }
}

我启用了 CORS,允许每个主机访问资源。

在 React 应用程序中,我将axios其用作我的 HTTP 库。这是对服务器的请求的示例:

interface LoginModel {
    email: string;
    password: string;
}

interface TokenAuthModel {
    successful: boolean;
    access_token: string;
}

import * as axios from 'axios';

const requestConfig = {
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
    },
        timeout: 15000
};

async login(login: LoginModel): Promise<TokenAuthModel | null> {
    const req = await axios.default.post('some-url', login, requestConfig);
    if (request.status === 200) {
        return request.data as TokenAuthModel;
    }
    return null;
}

它返回以下错误消息:

从源“http://localhost:3000”访问“https://app-name.herokuapp.com/some/endpoint”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

如上所述,该错误仅在从 React 前端发出请求时出现,而 Postman 调用按预期工作。

任何形式的帮助将不胜感激。

标签: reactjskotlinaxioscorsktor

解决方案


我将它用于cors:

install(CORS) {
        method(HttpMethod.Options)
        method(HttpMethod.Put)
        method(HttpMethod.Delete)
        method(HttpMethod.Patch)
        header(HttpHeaders.Authorization)
        header(HttpHeaders.ContentType)
        // header("any header") if you want to add any header
        allowCredentials = true
        allowNonSimpleContentTypes = true
        anyHost()
    }

推荐阅读