reactjs - 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 调用按预期工作。
任何形式的帮助将不胜感激。
解决方案
我将它用于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()
}
推荐阅读
- excel - 如何计算非静态数据透视表上最大/最小日期之间的差异?
- docker - 使用命令启动或运行 docker 容器
- django - serializer_class django todo 应用程序上的断言错误
- c - 了解 Tokyo Cabinet 中的 tchdbfwmkeys 方法(获取数据库中的前向匹配键)
- c++ - 如何实现 If-Else 条件模板?
- odoo - 如何根据 SO 中的状态隐藏“打印”下拉按钮
- git - 在 Android Studio 中注册 CredentialsProvider
- python - 如何通过制作 2 列将字符串写入 Python 中的 CSV 文件?
- java - 存储访问框架 - DocumentsContract 的某些方法在包含在我的 Android 应用程序中时未编译
- windows - 命令提示符中没有时间戳