Ktor后端的CORS问题 [英] CORS Issue With Ktor Backend

查看:88
本文介绍了Ktor后端的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a full-stack application with backend being developed in Ktor (Kotlin) and frontend in React (TypeScript). The backend is being hosted on Heroku, while the frontend is still under development, therefore I'm running it locally.

该API可以正常运行,并且在与Postman进行测试时可以正常工作.这是Ktor配置的一部分:

The API is operational and works as intended when tested with Postman. This is an excrept of the Ktor's configuration:

@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,允许每个主机访问资源.

I've enabled CORS, allowing every host to access the resources.

在React应用程序中,我使用 axios 作为我的HTTP库.这是向服务器发出请求的示例:

In React application, I'm using axios as my HTTP library. This is a sample of how a request to the server looks like:

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;
}

返回以下错误消息:

CORS策略已阻止从来源"http://localhost:3000"访问"https://app-name.herokuapp.com/some/endpoint"处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:所请求的资源上没有"Access-Control-Allow-Origin"标头.

Access to XMLHttpRequest at 'https://app-name.herokuapp.com/some/endpoint' from origin 'http://localhost:3000' 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.

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

As stated above, the error is only present when making a request from the React frontend, while Postman calls work as intended.

任何帮助将不胜感激.

推荐答案

我设法找到了解决问题的方法,但是解决方法似乎与在Heroku上托管后端应用程序有关,似乎需要使用该方法代理网址.您可以在此线程中了解更多信息.

I managed to find a solution to my problem, but the workaround seems to be tied to hosting the backend application on Heroku, where it seems like you need to use the proxy URL. You can read more about it in this thread.

首先,我将后端中的CORS模块修改为

First of all, I have modified the CORS module in my backend to

install(CORS) {
    method(HttpMethod.Options)
    method(HttpMethod.Put)
    method(HttpMethod.Delete)
    method(HttpMethod.Patch)

    // Beware that this is not recommended for production,
    // but I'm just using it during development
    anyHost()
}

但真正的窍门在前端:在API的基本URL前面加上代理URL .如果API的基本URL是 https://my-awesome-app.herokuapp.com/,则需要在其前面加上 https://cors-anywhere.herokuapp.com/,因此最终您的请求网址如下所示:

but the real trick comes on the frontend side: prefix the API's base URL with the proxy URL. If the API's base URL is https://my-awesome-app.herokuapp.com/, you need to prepend it with https://cors-anywhere.herokuapp.com/, so that ultimately your request URL looks like this:

https://cors-anywhere.herokuapp.com/https://my-awesome-app.herokuapp.com/

这篇关于Ktor后端的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆