【问题标题】:How do I get CORS working with golang chi server?如何让 CORS 与 golang chi 服务器一起工作?
【发布时间】:2020-04-05 06:25:39
【问题描述】:

我正在尝试针对 golang chi 服务器 (https://github.com/go-chi/chi) 获取跨源请求。浏览器发出的预检请求未获得预期的标头(下面的屏幕截图)。 这是一个设置简单 go server 和 express server 的脚本

go mod init
cat > main.go <<EOF
package main

import (
    "net/http"
    "github.com/go-chi/chi"
    "github.com/go-chi/cors"
)

func main() {
    r := chi.NewRouter()

    cors := cors.New(cors.Options{
    AllowedOrigins:   []string{"*"},
    // AllowOriginFunc:  func(r *http.Request, origin string) bool { return true },
    AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
    AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
    ExposedHeaders:   []string{"Link"},
    AllowCredentials: true,
    MaxAge:           300, // Maximum value not ignored by any of major browsers
    })
    r.Use(cors.Handler)    
    r.Post("/blogs", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("{\"Ack\": \"OK\"}"))
    })
    http.ListenAndServe(":8888", r)
}
EOF
go mod tidy
go build -o test-server
# Setup an express web server
npm init -y
npm install express --save
cat > server.js <<EOF
var express = require('express');
var app = express();

app.use('/', express.static(__dirname));
app.listen(3000, function() { console.log('listening')});
EOF
cat > index.html <<EOF
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script>
    document.addEventListener("DOMContentLoaded", function (event) {
        var payload = { blog: "example" }
        fetch('http://localhost:8888/blogs', {
            method: 'post',
            body: JSON.stringify(payload),
            headers: {
                "Content-Type": "application/json",
                "X-PINGOTHER": "pingpong"
            }
        })
            .then((response) => {
                return response.json();
            })
            .then((data) => {
                console.log(data);
            });
    });
</script>

<body>
</body>

</html>
EOF

在一个目录中运行上述脚本,然后从另一个选项卡执行“npm start”,然后执行“./test-server”。在 Chrome 中导航到“http://localhost:3000/”。打开Chrome开发者工具查看错误

See the screen shot

【问题讨论】:

    标签: go cors go-chi


    【解决方案1】:

    在这个例子中,我能够让 go-chi 服务器返回预期的标头

    Access-Control-Allow-Credentials: true
    Access-Control-Allow-Origin: http://localhost:3000
    Access-Control-Expose-Headers: Link
    

    通过将 X-PINGOTHER 添加到 Cors 处理程序中间件的选项中。

    AllowedHeaders:   []string{"X-PINGOTHER", "Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
    

    【讨论】:

      猜你喜欢
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      相关资源
      最近更新 更多