2

I am trying to get cross origin request working against a golang chi server (https://github.com/go-chi/chi). The preflight request made by the browser isn't getting the expected headers (screen shot below). Here is a script that sets up a simple go server and 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

Run the above script in a directory and execute 'npm start' followed by './test-server' from another tab. Navigate to 'http://localhost:3000/' in Chrome. Open Chrome developer tool to view the error

See the screen shot

ajith
  • 37
  • 1
  • 4

2 Answers2

0

In this example, I was able to get go-chi server to return the expected headers

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

by adding X-PINGOTHER to the Cors handler middleware's options.

AllowedHeaders:   []string{"X-PINGOTHER", "Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ajith
  • 37
  • 1
  • 4
0

The general idea behind the issue (and solution made by author later) is: check Access-Control-Request-Headers which presented in the request headers and AllowedHeaders which your go-chi server supports.

Absolutely every header from Access-Control-Request-Headers must be presented in AllowedHeaders, even if one of them is missed - you'll get Access-Control-Allow-Origin missed from the response headers.

Hope it will help.

Wishmaster
  • 1,102
  • 14
  • 20