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