我已经在开发中成功启用了CORS。我的Golang后端与本地计算机上的Angular前端通信良好。但是,我不知道如何在生产中启用CORS(DigitalOcean上的Ubuntu)。我在Firefox上得到了这个:

“跨域请求被阻止:同源策略禁止读取位于http:// localhost:12345 /anteroom的远程资源。(原因:CORS请求未成功)。”

我正在使用systemd单元运行Golang后端,并在localhost:12345提供服务。

--prodproxy_pass

我正在使用的版本:Ubuntu 16.04,PM2 3.3.1,Angular CLI 7.3.4,angular-http-server 1.8.1。

当前端尝试将JSON数据发布到后端时,就会发生问题(如上面的消息所示,localhost:12345 / anteroom)。

我读过CORS是服务器端的问题。因此,我尝试在有服务器的任何地方(即后端Nginx和angular-http-server)启用它。

在我的Golang代码中启用了该功能:

func anteroom(res http.ResponseWriter, req *http.Request) {
    res.Header().Set("Access-Control-Allow-Origin", "*")
    res.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
    res.Header().Set("Access-Control-Allow-Headers", "Content-Type")
    res.Header().Set("Content-Type", "application/json")
...
}

func main() {
    ...
    # Using Gorilla mux router.
    router := mux.NewRouter()
    router.HandleFunc("/anteroom", anteroom).Methods("POST", "OPTIONS")
}
ng serve
--cors
pm2 start $(which angular-http-server) --name app -- --path /PATH/TO/DIST -p 8080 --cors

我还尝试过在与Angular前端构建有关的Nginx文件中启用它(从此处改编):

location / {
if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type';
        add_header 'Content-Type' 'application/json';
        return 204;
     }

     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type';
        add_header 'Content-Type' 'application/json';
     }

     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type';
     }
proxy_pass http://localhost:8080;
}
}

我看过PM2,angular-http-server,Nginx和许多其他内容的文档,但我不知道自己缺少什么。让我知道?谢谢。