flutter - http 请求被 Flutter Web 的 Cors 策略阻止
问题描述
我有一个使用 php 作为后端的 Android、Ios 和网络应用程序。所有 Api 在 android 和 ios 中都运行良好,但在 web.xml 中抛出 CORS 错误。得到这样的错误
从源“http://localhost:49168”访问“https://example.com/api”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头.
我尝试将标头:{'Access-Control-Allow-Origin': 'http://localhost:49168', "Origin": "http://localhost:49168" } 发送到 http 请求。如果我为 chrome 添加 CORS 扩展,Web 工作顺利。请帮帮我
解决方案
两周前同样的问题袭击了我。对我来说,以下错误给了我检查问题的错误方向:
从源“http://localhost:49168”访问“https://example.com/api”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头.
它说了一些关于请求的内容,但事实证明它与请求无关。apache
它也与网络服务器(或nginx
在我的情况下)无关。
解决方案是从后端向响应(是的response )添加标头。我不知道php
代码的解决方案,但我在我的 golang 后端使用以下代码将标头添加到响应中:
// Adding CORS header to response.
func (server *WebUploadServer) addCorsHeader(res http.ResponseWriter) {
headers := res.Header()
// use your domain or ip address instead of "*".
// Using "*" is allowing access from every one
// only for development.
headers.Add("Access-Control-Allow-Origin", "*")
headers.Add("Vary", "Origin")
headers.Add("Vary", "Access-Control-Request-Method")
headers.Add("Vary", "Access-Control-Request-Headers")
headers.Add("Access-Control-Allow-Headers", "Content-Type, Origin, Accept, token")
headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
}
// Here we handle the web request.
func (server *WebUploadServer) webHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint hit")
server.addCorsHeader(w) // Here, we add the header to the response
switch r.Method {
case "POST":
// do something here.
case "OPTIONS":
w.WriteHeader(http.StatusOK)
case "GET":
fallthrough
default:
fmt.Fprintf(w, "Sorry, only POST method is supported.")
}
}
推荐阅读
- powershell - 如何使用 PowerShell 脚本从分发列表中获取用户作为非交换管理员或非租户管理员?
- wordpress - Woocommerce 防止自定义表单字段被订单搜索
- twitter - 如何使用 twitter API 检索用户最近 7 天的推文?
- r - 如何从闪亮的应用程序中获取选定属性的聚合数据?
- php - 未找到错误类“App\User”。在通过作曲家进行全新身份验证安装后
- sql - 案例转换号到字符 Oracle SQL
- javascript - 如何将文本框输入设置为变量
- flask - Flask-RESTX - 响应正文中的阿拉伯文本
- c# - 如何实现依赖于Action和Func的接口?当 Func 返回时,动作实现不返回任何内容
- java - Java Flight Recorder 针对 OpenJDK 8 和 OpenJDK 11 的 VM 选项的完整列表