Yas*_*ava 7 ajax cross-domain go cors
嗨,我正在实施rest apis,为此我想要允许交叉原始请求.
我目前在做什么:
AWS上的Go-server代码:
func (c *UserController) Login(w http.ResponseWriter, r *http.Request, ctx *rack.Context) {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
...
...
c.render.Json(w,rsp, http.StatusOK)
return
}
Run Code Online (Sandbox Code Playgroud)
localhost上的Ajax代码:
<script>
$( document ).ready(function() {
console.log( "ready!" );
$.ajax({
url: 'http://ip:8080/login',
crossDomain: true, //set as a cross domain requests
withCredentials:false,
type: 'post',
success: function (data) {
alert("Data " + data);
},
});
});
Run Code Online (Sandbox Code Playgroud)
我在浏览器控制台上收到以下错误: XMLHttpRequest无法加载http:// ip:8080/login.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:8081 '访问.响应具有HTTP状态代码422.
我尝试添加预检选项:
func corsRoute(app *app.App) {
allowedHeaders := "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization,X-CSRF-Token"
f := func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
w.Header().Set("Access-Control-Expose-Headers", "Authorization")
}
return
}
app.Router.Options("/*p", f, publicRouteConstraint)
}
Run Code Online (Sandbox Code Playgroud)
但它没有用.
可以做些什么来解决它.
yu *_*ian 13
我用gorilla/mux
package来构建Go RESTful API服务器,客户端使用JavaScript Request可以工作,
我的Go Server运行于localhost:9091
,以及服务器代码:
router := mux.NewRouter()
//api route is /people,
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeopleAPI).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))
Run Code Online (Sandbox Code Playgroud)
我发现在OPTIONS
这里给予很重要,否则会发生错误:
选项http:// localhost:9091/people 405(方法不允许)
无法加载http:// localhost:9091/people:对预检请求的响应未通过访问控制检查:请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许来源" http:// localhost:9092 "访问.响应具有HTTP状态代码405.
允许OPTIONS
之后效果很好.我从本文中得到了这个想法.
此外,MDN CORS文档提到:
此外,对于可能对服务器数据造成副作用的HTTP请求方法,规范要求浏览器"预检"请求,使用HTTP OPTIONS请求方法从服务器请求支持的方法,然后在服务器"批准"时,使用实际的HTTP请求方法发送实际请求.
以下是api GetPeopleAPI方法,注意方法我给出评论//允许CORS在这里*或具体来源,我有另一个类似的答案解释CORS的概念在这里:
func GetPeopleAPI(w http.ResponseWriter, r *http.Request) {
//Allow CORS here By * or specific origin
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
// return "OKOK"
json.NewEncoder(w).Encode("OKOK")
}
Run Code Online (Sandbox Code Playgroud)
在客户端,我使用带有javascript的html localhost:9092
,javascript将向服务器发送请求localhost:9092
function GetPeople() {
try {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:9091/people", false);
xhttp.setRequestHeader("Content-type", "text/html");
xhttp.send();
var response = JSON.parse(xhttp.response);
alert(xhttp.response);
} catch (error) {
alert(error.message);
}
}
Run Code Online (Sandbox Code Playgroud)
并且请求可以成功获得响应"OKOK"
.
您还可以通过类似工具检查响应/请求标头信息Fiddler
.
小智 7
谢谢你的线索 - 这一切都在标题中!我在服务器端只使用这些golang标头:
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
Run Code Online (Sandbox Code Playgroud)
现在使用这个JQuery:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$.ajax({
type: 'GET',
url: 'https://www.XXXXXXX.org/QueryUserID?u=juXXXXny&p=blXXXXXne',
crossDomain: true,
dataType: 'text',
success: function(responseData, textStatus, jqXHR) {
alert(responseData);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
小智 7
进入服务器设置:
package main
import (
"net/http"
)
func Cors(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=ascii")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers","Content-Type,access-control-allow-origin, access-control-allow-headers")
w.Write([]byte("Hello, World!"))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/plm/cors",Cors)
http.ListenAndServe(":8081", mux)
}
Run Code Online (Sandbox Code Playgroud)
客户端 JQUERY AJAX 设置:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<br> Please confirm to proceed : <button class="myConfirmButton1">Go!!</button>
<div id="loader1" style="display:none;">loading...</div>
<div id="loader2" style="display:none;">...done</div>
<div id="myFeedback1"></div>
<script>
$(document).ready(function(){
$(".myConfirmButton1").click(function(){
$('#loader1').show();
$.ajax({
url:"http://[webserver.domain.com:8081]/plm/cors",
dataType:'html',
headers: {"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "access-control-allow-origin, access-control-allow-headers"},
type:'get',
contentType: 'application/x-www-form-urlencoded',
success: function( data, textStatus, jQxhr ){
$('#loader1').hide();
$('#loader2').show();
$('#myFeedback1').html( data );
},
error: function( jqXhr, textStatus, errorThrown ){
$('#loader1').hide();
$('#myFeedback1').html( errorThrown );
alert("error" + errorThrown);
}
});
});
});
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
带有 curl 的客户端测试请求并获得响应:
curl -iXGET http://[webserver.domain.com:8081]/plm/cors
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Content-Type,access-control-allow-origin, access-control-allow-headers
Access-Control-Allow-Origin: *
Content-Type: text/html; charset=ascii
Date: Wed, 17 Jan 2018 13:28:28 GMT
Content-Length: 13
Hello, World!
Run Code Online (Sandbox Code Playgroud)
为了允许CORS,您的服务器应该捕获浏览器在使用 OPTIONS 方法进行实际查询之前发送到同一路径的所有预检请求。
第一种方法是通过这样的方式手动管理:
func setupCORS(w *http.ResponseWriter, req *http.Request) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
func indexHandler(w http.ResponseWriter, req *http.Request) {
setupCORS(&w, req)
if (*req).Method == "OPTIONS" {
return
}
// process the request...
}
Run Code Online (Sandbox Code Playgroud)
第二种方法是使用准备好的第三方 pkg,如https://github.com/rs/cors
package main
import (
"net/http"
"github.com/rs/cors"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"hello\": \"world\"}"))
})
// cors.Default() setup the middleware with default options being
// all origins accepted with simple methods (GET, POST). See
// documentation below for more options.
handler := cors.Default().Handler(mux)
http.ListenAndServe(":8080", handler)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
31178 次 |
最近记录: |