I'm having trouble with a CORS policy error when sending a fetch POST request to my Golang AppEngine API. Although I don't understand why this error is occurring. Below is the code I'm using:
Below is the Angular code calling the API:
private async sendHTTPPut(data: UserInfo, func: string) {
let requestHeaders = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } as HeadersInit;
console.log(requestHeaders)
return await fetch(
this.endpoint + func,
{
method: 'POST',
headers: requestHeaders,
body: JSON.stringify(data),
mode: "cors"
}
)
}
Here is the server code handling CORS:
func StartApp() {
router = mux.NewRouter()
router.HandleFunc("/", hello)
router.HandleFunc("/hello", hello)
router.HandleFunc("/AcceptMember", AcceptMember)
router.HandleFunc("/CreateTeam", CreateTeam)
router.HandleFunc("/Leave", Leave)
router.HandleFunc("/InviteMember", InviteMember)
router.HandleFunc("/BeginSignup", BeginSignup)
router.HandleFunc("/ProcessSignup", ProcessSignup)
router.HandleFunc("/CompleteSignup", CompleteSignup)
// Scoring
router.HandleFunc("/GetLocalScore", GetLocalScore)
allowedOrigins := handlers.AllowedOrigins([]string { "* always" })
allowedHeaders := handlers.AllowedHeaders([]string { "Content-Type" })
if err := http.ListenAndServe(":8080", handlers.CORS(allowedOrigins, allowedHeaders)(router)); err != nil {
log.Fatal(err)
}
}
Shown below is the request sent to the server:
Request URL: http://localhost:8080/BeginSignup
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Access-Control-Allow-Origin: *
Content-Type: application/json
Referer: http://localhost:4200/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.68
PAYLOAD
{member: {phoneNum: "0648503047"},…}
member: {phoneNum: "0648503047"}
score: null
team: {teamName: ".None", teamMembers: ["0648503047"], teamLeader: "0648503047"}
Here is the response received from the server:
Request URL: http://localhost:8080/BeginSignup
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Content-Length: 0
Date: Mon, 05 Oct 2020 20:34:51 GMT
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: access-control-allow-origin,content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:8080
Origin: http://localhost:4200
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.68