如何让CORS与golang chi服务器一起工作?

vdzxcuhz  于 2023-03-10  发布在  Go
关注(0)|答案(2)|浏览(142)

我正在尝试在golang chi服务器(https://github.com/go-chi/chi)上运行跨源请求,浏览器发出的preflight请求没有得到预期的头(下面的屏幕截图),下面是一个脚本,它设置了一个简单的go服务器和express服务器

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

enxuqcxy

enxuqcxy1#

在本例中,我能够让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"},
pgccezyw

pgccezyw2#

该问题背后的总体思路(以及作者随后提出的解决方案)是:检查Access-Control-Request-Headers出现在request报头中,并且检查您的围棋服务器支持的AllowedHeaders
Access-Control-Request-Headers中的每个头都必须在AllowedHeaders中显示,即使其中一个头丢失了-您将得到响应头中丢失的Access-Control-Allow-Origin
希望能有所帮助。

相关问题