跨域跨域跨域golang与angularjs的默契

go-json-rest (golang)

启动CORS中间件,指定origin跨域,origin这里填写对应域名即可

直接跨所有域名,return origin == req.Header.Get(“Origin”),即可

func main() {
    //.......
        api := rest.NewApi()
        api.Use(rest.DefaultDevStack...)
        //配置API跨域CORS
        api.Use(&rest.CorsMiddleware{
                RejectNonCorsRequests: false,
                OriginValidator: func(origin string, request *rest.Request) bool {
                        return origin == "http://localhost:8100"
                },
                AllowedMethods: []string{"GET", "POST", "PUT"},
                AllowedHeaders: []string{
                        "Accept", "Content-Type", "X-Custom-Header", "Origin"},
                AccessControlAllowCredentials: true,
                AccessControlMaxAge:           3600,
        })
    //......

angularjs

加withCredentials: ture,加内容类型application/json

    // Login
    req = {
        withCredentials: true,
        method: 'POST',
        url: 'http://127.0.0.1:8080/countries',
        headers: {
        'Content-Type': 'application/json'
        //'Content-Type': 'text/plain'
        },
        data: { "username": "test", "password": "123456" },
    }
    $http(req).
        success(function(data, status, headers, config) {
        console.log("OK");

        }).
        error(function(data, status, headers, config) {
        console.log("Shit");

        });

微信扫一扫交流

作者:ryanemax
微信关注:ryanemax (刘雨飏)
本文出处:https://futurestack.cn/cookbook/api/goangularfaq/
授权协议: CC BY-SA 4.0