1

I have next Go code:

package main

import (
  "database/sql"
  "encoding/json"
  "fmt"
  "net/http"

  _ "github.com/go-sql-driver/mysql"
  "github.com/labstack/echo"
  "github.com/labstack/echo/middleware"
)

func main() {
  // Echo instance
  e := echo.New()

  // Middleware
  e.Use(middleware.Logger())
  e.Use(middleware.Recover())
  e.Use(middleware.CORS())
  e.POST("/createuser", addUser)
  e.Logger.Fatal(e.Start(":4000"))
}

And Vue js fetch script

const res = await fetch('https://localhost:4000/createuser', {
    method: 'POST',
    headers: {
      'Content-type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    },
    body: JSON.stringify(nameAndPhone),
  })

Errors in my Firefox console when executing it

Extraneous request blocked: Single source policy denies reading remote resource at https://localhost:4000/createuser (Reason: Failed to complete CORS request).
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

My Network tab:

Blocked OPTIONS localhost:4000 createuser fetch CORS failed          0byte
Blocked POST    localhost:4000 createuser fetch NS_ERROR_DOM_BAD_URI 0byte

It works in Postman, but doesn't work from browser because of CORS. Why doesn't it work if I already have e.Use(middleware.CORS()) in my code?

Hakan Dilek
  • 2,178
  • 2
  • 23
  • 35
undernet
  • 57
  • 1
  • 8
  • This samples could be helpful. [Cookbook](https://echo.labstack.com/cookbook/cors/) – Gealber Jul 02 '21 at 15:00
  • @Gealber checked it before thanks. I guess I found a reason: don't see 'middleware' dependency in go sum. Looking for solution of how to reinstall it – undernet Jul 02 '21 at 15:48

2 Answers2

4

Please follow the next example.

e := echo.New()
    e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
      AllowOrigins: []string{"*"},
      AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
    }))  
Eddwin Paz
  • 2,842
  • 4
  • 28
  • 48
1

The problem was I was fetching from https and not http

Fixed js:

const res = await fetch('http://localhost:4000/createdebter', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-type': 'application/json',
        },
        body: JSON.stringify(nameAndPhone),
      })
undernet
  • 57
  • 1
  • 8