即使主域相同,跨源请求也被阻止

I am working on an application that use image uploading functionality. The application back end is written in Golang where as front end is in Angular4. I am using Gin framework to run http requests in Golang.

Following is the Golang code to upload image:

func UploadFile(c *gin.Context){
    imageData := make(map[string]interface{})
    response := ResponseController{}

    /* ------ Get current date ------ */
    currDate        := time.Now().UTC()
    yearString      := strconv.Itoa(currDate.Year())
    monthString     := strconv.Itoa(int(currDate.Month()))
    dayString       := strconv.Itoa(currDate.Day())

    path := config.UploadBasePath+config.AppFolder+config.UploadsFolder+yearString+"/"+monthString+"/"+dayString+"/"

    /* create temp directory if does not exist */
    if _, err := os.Stat(path); os.IsNotExist(err) {
        os.MkdirAll(path, 0755)
    }

    /* read data from form */
    file, err := c.FormFile("file")
    if err != nil {
        response = ResponseController{
            config.FailureCode,
            config.FailureFlag,
            "Error while reading image.",
            nil,
        }
        GetResponse(c, response)
        return
    }
    filePath := path+file.Filename
    if err := c.SaveUploadedFile(file, filePath); err != nil {
        response = ResponseController{
            config.FailureCode,
            config.FailureFlag,
            "Error while uploading image.",
            err,
        }
        GetResponse(c, response)
        return
    }
    uploadUrl := "/"+config.UploadsFolder+yearString+"/"+monthString+"/"+dayString+"/"+file.Filename
    imageData["upload_url"] = uploadUrl

    response = ResponseController{
        config.SuccessCode,
        config.SuccessFlag,
        "Image uploaded successfully.",
        imageData,
    }
    GetResponse(c, response)
}

The front end and back end are on same domain having subdomains also. When request generate from front end.

I have passed following headers in Golang code:

c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

Still when I am uploading image, it returns following error in console and image is not getting uploaded:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://SUBDOMAIN.DOMAIN:8080/api/v1/upload. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://[DOMAIN-NAME].com’).

Can anyone guide me what I am missing here. Thanks!

Try to set the OPTIONS in your router router.HandleFunc("/", getModulos).Methods("POST", "GET", "OPTIONS")

You can put the CONTENT-TYPE too like this w.Header().Set("Access-Control-Allow-Headers", "Content-Type")