我正在尝试从我的前端向 API 应用程序发送 GET 请求。两者都在我的本地机器上运行。这就是它现在的构建方式:
backend <===> frontend <=x=> API application
所有这三个部分都在各自的 docker 容器中彼此独立运行,并且仅通过 HTTP 请求相互通信。
如上图所示,backend
和 frontend
之间的连接工作正常,但 frontend
和 API application
没有。
堆栈包括:
frontend
:使用 vue-js 的节点服务器,对于请求我使用 axiosAPI 应用程序
:带有 Play Framework 2.5.14 的 Scala
当我像这样通过 curl 向她发送请求时,API 应用程序本身就可以工作:
curl -X GET api-application.docker/api/user?userId=1 \
-H "Authorization: key" -H "Accept: Application/Json"
但是当我从前端调用它时,我在 OPTIONS 调用中收到 404。它还在 Firefox 中给了我一个与 CORS header 相关的警告 Access-Control-Allow-Origin
:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the
remote resource at http://api-application.docker:9000/api/user?userId=1
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
因此我首先进入了 api 应用程序的 application.conf
并添加了
play.filters.cors {
allowedOrigins = ["*"]
}
我还尝试将星号换成http://frontend.docker:8080
这没有用,所以我再次删除了该条目并添加了这一行:
play.filters.disabled += "play.filters.cors.CORSFilter"
仍然没有任何变化。现在我想知道我是否误解了 OPTIONS 和 CORS 之间的联系?还是我关错了?谁能帮帮我?
编辑: 我在等待答案时尝试了更多的东西,但都没有成功:
我将 application.conf
中的条目更改为:
play.filters.cors {
allowedOrigins = null
}
最佳答案
OPTIONS 请求上的 404 表示您的 CORSFilter
未启用。由于您使用的是 Play 2.5,您可以 enable通过添加
libraryDependencies += filters
到您的 build.sbt
,并通过创建以下 app/Filters.scala
文件:
import javax.inject.Inject
import play.api.http.DefaultHttpFilters
import play.filters.cors.CORSFilter
class Filters @Inject() (corsFilter: CORSFilter)
extends DefaultHttpFilters(corsFilter)
默认情况下,所有内容都是允许的,因此在您决定开始锁定访问之前无需修改 application.conf
。您不应添加 play.filters.disabled += "play.filters.cors.CORSFilter"
,因为这会禁用 CORS 支持。
curl
请求正常工作的原因是因为非浏览器 HTTP 客户端不执行同源策略(参见 related SO answer),因此 CORS 不适用于 curl
。
OPTIONS 请求上的 404 表示未找到以下路由:
OPTIONS api-application.docker/api/user
浏览器自动发送这个preflight request在发送相应的 GET 请求之前。一旦启用,此 OPTIONS 路由将由 Play 的 CORS 支持自动处理。
关于vue.js - 选项请求失败,返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50213753/