I have built an app with angular 5 which connects to a REST API developed with golang and hosted on an aws ec2 instance running on port 8080. My angular frontend code creates a POST request, and before making that request, the browser first sends a COR preflight request, which fails with the following error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at
https://signup.mysite.com:8080/api/v1/merchant/signup
. (Reason: missing token ‘access-control-allow-credentials’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
The following headers are sent by the browser in the OPTIONS request to the REST API server:
Access-Control-Request-Headers : access-control-allow-credentia…rol-allow-origin,content-type
Access-Control-Request-Method : POST
Cors are enabled on golang but not sure if they are working. How can I resolve the issue
EDIT Using following code to add header in post request in angular 5
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
let headers = new HttpHeaders();
headers = headers.append('Access-Control-Allow-Origin', '*');
headers = headers.append('Access-Control-Allow-Credentials', 'true');
return this.http.post<Response>(this.apiUrl+'merchant/signup', JSON.stringify(formValues),{headers: headers}).map(response => response.response);'true');
Following code is in go file
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// host := strings.Split(c.Request.Host, ":8080")
c.Writer.Header().Set("Content-Type", "application/json")
// c.Writer.Header().Set("Access-Control-Allow-Origin", "http://"+host[0])
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
// c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Ip, X-Requested-With, access-control-allow-credentials ")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
}
also using cores package
router.Use(cors.Default())