So I have a domain name which is a static html file that sends an ajax request to a subdomain app which is behind Nginx in a reverse proxy.
Here is my ajax code:
$(document).ready(function(){
function call() {
$.ajax({
type: "POST",
url: "https://test.example.com/call",
crossDomain: true,
data: $("#form-call").serialize(),
success: function(response) {
$("#response").html(response);
},
error: function() {
alert("error");
}
});
And on Nginx I have:
upstream example {
server 192.168.1.10:6000;
}
server {
listen 443;
server_name test.example.com;
ssl on;
ssl_certificate /etc/nginx/ssl/afs.crt;
ssl_certificate_key /etc/nginx/ssl/afs.key;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Authorization "";
client_max_body_size 0;
chunked_transfer_encoding on;
add_header 'Access-Control-Allow-Origin' "$http_origin";
location / {
proxy_pass https://exapmle;
proxy_read_timeout 900;
}
}
And I have this on my golang app to help with CORS:
func (s *MyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if origin := req.Header.Get("Origin"); origin != "" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
rw.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
// Stop here if its Preflighted OPTIONS request
if req.Method == "OPTIONS" {
return
}
// Lets Gorilla work
s.r.ServeHTTP(rw, req)
}
It works fine on chrome, but on firefox I get the error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://test.example.com/call. This can be fixed by moving the resource to the same domain or enabling CORS.
DISCLAIMER: I have just seen how old this post is, I imagine the problem has already been solved.
This worked for me:
func corsHandler(fn http.HandleFunc) http.HandleFunc {
return func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Access-Control-Allow-Origin", "*")
fn(rw, req)
}
}
Then when setting up your routers you can:
r := mux.NewRouter()
r.HandleFunc("/<route>", corsHandler(handleRouteMethod)).Methods("<METHOD>")
Slightly different approach but it has definitely worked, so if all else fails, you could give it a try (this assumes you are using gorilla mux, if you are using the httprouter or something else then your corsHandler method maybe needs to use a different function signature).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.