React fetch请求Play Scala接口报CORS跨域错误该如何修复?
问题修复步骤
1. 修正前端fetch代码
Access-Control-Allow-Origin是服务端返回的响应头,前端不需要也不能主动在请求头中添加,否则会触发额外的预检校验,修正后的代码如下:
function signOut() { const host = "http://localhost:9000/" const route = "signOut"; const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json'}, credentials: 'include', mode: 'cors', }; return fetch(host + route, requestOptions).then((response) => response.json()) }
2. 修正Play后端application.conf配置
现有配置存在3处核心错误,按如下规则修正:
- 删掉多余的错误配置行
enables += play.filter.cors.CorsFilter,CORSFilter已经在play.filters.enabled中完成注册 - 将cors配置块移到
play.filters内部,确保配置被正确加载 - 修正HTTP方法拼写错误:
OPTION改为OPTIONS,预检请求默认使用OPTIONS方法,未放行会直接拦截 - 新增
allowedCredentials = true配置,适配前端带Cookie的跨域请求场景
修正后的完整配置如下:
play.filters { # Enabled filters are run automatically against Play. # CSRFFilter, AllowedHostFilters, and SecurityHeadersFilters are enabled by default. enabled += filters.ExampleFilter enabled += play.filters.cors.CORSFilter # Disabled filters remove elements from the enabled list. #disabled += filters.ExampleFilter cors { # Filter paths by a whitelist of path prefixes #pathPrefixes = ["/some/path", ...] # 适配带凭证的跨域请求 allowedCredentials = true # The allowed origins. If null, all origins are allowed. #allowedOrigins = ["https://www.example.com"] allowedOrigins = ["http://localhost:3000"] # The allowed HTTP methods. If null, all methods are allowed #allowedHttpMethods = ["GET", "POST"] allowedHttpMethods = ["GET", "POST", "PUT", "PATCH", "OPTIONS", "DELETE"] # 放行常用请求头,可根据实际业务扩展 allowedHttpHeaders = ["Content-Type", "Accept"] } }
3. 异常场景补充校验
如果完成以上修改后仍然报错,检查两个常见问题:
- Play默认开启CSRF校验,带Cookie的POST请求需要要么给
/signOut接口添加CSRF豁免,要么前端在请求头中携带后端返回的CSRF Token - 确认你的路由配置没有拦截OPTIONS请求,CORSFilter会自动处理预检请求,不需要手动编写OPTIONS接口逻辑
内容的提问来源于stack exchange,提问作者duckduckgoes
相关产品推荐
相关产品推荐

