gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:36:41 25 4
gpt4 key购买 nike

我正在尝试针对 golang chi 服务器 ( https://github.com/go-chi/chi ) 获取跨源请求。浏览器发出的预检请求未获得预期的 header (下面的屏幕截图)。
这是一个设置简单的 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”。导航到“ http://localhost:3000/ ' 在 Chrome 中。打开 Chrome 开发者工具查看错误

See the screen shot

最佳答案

在此示例中,我能够让 go-chi 服务器返回预期的 header

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"},

关于go - 如何让 CORS 与 golang chi 服务器一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61031223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com