[gogf/gf]跨域请求时 OPTIONS 方法匹配不到路由

2024-06-25 443 views
3

最新

s := g.Server()
s.BindMiddlewareDefault(func(r *ghttp.Request) {
    fmt.Println("cors")
    r.Response.CORSDefault()
    r.Middleware.Next()
})

在发送请求时,发现 OPTIONS 不能匹配到任务路由,直接返回 404

// 跨域请求成功,并且 go 打印了 cors
$.ajax('http://localhost:8010/api/captcha',{ method:'GET'})

// 请求失败 404,没有运行中间件
$.ajax('http://localhost:8010/api/captcha',{ method:'OPTIONS'})

回答

6

@lvshutao 我使用以下代码测试没有出现你所说的问题:

package main

import (
    "fmt"
    "github.com/gogf/gf/frame/g"
    "github.com/gogf/gf/net/ghttp"
)

func main() {
    s := g.Server()
    s.BindMiddlewareDefault(func(r *ghttp.Request) {
        fmt.Println("cors")
        r.Response.CORSDefault()
        r.Middleware.Next()
    })
    s.BindHandler("/api/captcha", func(r *ghttp.Request) {
        r.Response.Write("captcha")
    })
    s.SetPort(8010)
    s.Run()
}
4

我看了下,你的第二个 "api/captcha" 使用的方法是 ALL。我项目中都是手动指定请求方法 (RESTful 风格),比如s.BindHandler("GET:/api/captcha",...),就会出现上面的问题了

4

@lvshutao 嗯,明白了,这个其实是初期中间件设计的时候只考虑有服务函数才会执行引起的,这块已经完善了,这两天我会发布一个小版本,到时候你再试试。

1
func AllMiddlewareCORS(r *ghttp.Request) {
    ops := r.Response.DefaultCORSOptions()
    ops.AllowHeaders = "*"
    r.Response.CORS(ops)
    if r.Request.Method == "OPTIONS" {
        r.Response.WriteStatus(http.StatusNoContent)
    } else {
        r.Middleware.Next()
    }
}
s := g.Server()
    //全局中间件
    s.AddMiddleware(middleware.AllMiddlewareCORS)
1

@lvshutao 请更新最新框架代码再试。

0

这个有用, 框架默认的方式不行, 还是404