Added CORS support for the monitoring server (#4423)

- [x] Link to issue, e.g. `Resolves #NNN`
 - [ ] Documentation added (if applicable)
 - [x] Tests added
- [ ] Branch rebased on top of current main (`git pull --rebase origin
main`)
- [ ] Changes squashed to a single commit (described
[here](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html))
 - [ ] Build is green in Travis CI
- [x] You have certified that the contribution is your original work and
that you license the work to the project under the [Apache 2
license](https://github.com/nats-io/nats-server/blob/main/LICENSE)

Resolves #4422 

### Changes proposed in this pull request:

- Added `Access-Control-Allow-Origin` header to allow CORS requests for
the monitoring server
- Added a check in the tests for the header when the `Content-Type` is
`application/json`
This commit is contained in:
Derek Collison
2023-08-25 14:49:09 -07:00
committed by GitHub
2 changed files with 9 additions and 1 deletions

View File

@@ -2313,6 +2313,7 @@ func ResponseHandler(w http.ResponseWriter, r *http.Request, data []byte) {
} else { } else {
// Otherwise JSON // Otherwise JSON
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(data) w.Write(data)
} }
} }

View File

@@ -157,7 +157,14 @@ func readBodyEx(t *testing.T, url string, status int, content string) []byte {
} }
ct := resp.Header.Get("Content-Type") ct := resp.Header.Get("Content-Type")
if ct != content { if ct != content {
stackFatalf(t, "Expected %s content-type, got %s\n", content, ct) stackFatalf(t, "Expected %q content-type, got %q\n", content, ct)
}
// Check the CORS header for "application/json" requests only.
if ct == appJSONContent {
acao := resp.Header.Get("Access-Control-Allow-Origin")
if acao != "*" {
stackFatalf(t, "Expected with %q Content-Type an Access-Control-Allow-Origin header with value %q, got %q\n", appJSONContent, "*", acao)
}
} }
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {