我在 Firebase 托管上托管一个单页应用程序,我需要允许对应用程序引擎的跨域请求。应用程序托管在project-id.firebaseapp.com 上,应用程序引擎服务托管在project-id.appspot.com 上。我把部署文档 https://firebase.google.com/docs/hosting/full-config#section-full-firebasejson并且没有示例如何为 URL 添加 Access-Control-Allow-Origin 标头。
这是我的 firebase.json 的样子:
{
"database": {
"rules": "database.rules.json"
},
"hosting": {
"public": "public",
"redirects": [
{
"source": "/server/:rest*",
"destination": "https://app-id.appspot.com/:rest*",
"type": 301
}
],
"rewrites": [
{
"source": "/views/**",
"destination": "/views/**"
},
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [ {
"source" : "https://app-id.appspot.com/registration/generate",
"headers" : [ {
"key" : "Access-Control-Allow-Origin",
"value" : "*"
} ]
} ]
}
}
我尝试使用 gsutils 设置 CORS,但它也没有帮助:
这是我的 cors.json
[
{
"maxAgeSeconds": 3600,
"method": ["GET", "POST"],
"origin": ["https://project-id.appspot.com/"]
}
]
提前致谢
解决方案:
如果您只想在静态文件上允许 CORS,那么在 app.yaml 中设置 Access-Control-Allow-Origin 标头就足够了。对于动态请求,此标头不允许出现在 app.yaml 中,因此您必须以编程方式添加它。
如果您的请求很简单,则以下代码有效:
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Content-Type", "text/csv");
resp.getWriter().append("Response");
}
但是,如果您的请求已预先处理,则必须重写 doOptions 方法并添加适当的标头:
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
resp.addHeader("Access-Control-Allow-Headers", "Content-Type");
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Content-Type", "text/csv");
resp.getWriter().append("Response");
}
Here https://www.html5rocks.com/static/images/cors_server_flowchart.png是一个有用的图表,它阐明了服务器上的 CORS 实现: