CORS golang echo framework

huangapple go评论71阅读模式
英文:

CORS golang echo framework

问题

我有以下Go代码:

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实例
    e := echo.New()

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

以及Vue.js的fetch脚本:

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

在执行时,我的Firefox控制台中出现以下错误:

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.

我的网络选项卡显示:

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

它在Postman中可以工作,但在浏览器中由于CORS而无法工作。为什么即使我已经在代码中使用了e.Use(middleware.CORS()),它仍然无法工作?

英文:

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?

答案1

得分: 4

请按照下面的示例进行操作。

e := echo.New()
    e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
      AllowOrigins: []string{"*"},
      AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
    }))
英文:

Please follow the next example.

e := echo.New()
    e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
      AllowOrigins: []string{"*"},
      AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
    }))  

答案2

得分: 1

问题是我从 https 获取而不是 http

修复后的 JavaScript 代码:

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

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),
      })

huangapple
  • 本文由 发表于 2021年7月2日 22:22:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/68226822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定