Cross origin request blocked even though primary domain is same

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!

I think you just forgot to set the Access-Control-Allow-Headers

w.Header().Add("Access-Control-Allow-Headers", "Access-Control-Allow-Origin")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Credentials", "true")

Also don’t forget check MIME type of file for more safety :slight_smile:

Seems that you must allow origin for the subdomain.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.