跨域访问

背景:

1、 在使用beego开发后台接口,nginx作为反向代理,ajax请求后台接口。
2 、 beego后台使用session需要验证用户是否登录,但在beego中使用cookie时,针对session默认使用 httponly, 使得session cookie 被存储在response header 中, js无法获取,所以无法用js读取cookie,请求接口时,返回给接口,达到验证。但是在使得session cookie信息,保存在请求时的request headers里,那么后台就可以验证session是否存在。

实现配置

1 在beego的controller函数中 (该服务在 外网服务器 A 上)。

package  controllers


import (
    "github.com/astaxie/beego"
)


type TestController struct {
    beego.Controller
}

func (this *RssController) Check() {
    returncode, msg := 0, "success"
    result :=  make(map[string]interface{})
   v := this.GetSession("editorname")
   if v == nil {
       returncode = 1
       msg  = "log out"
   }
   result["returncode"] = returncode
   result["message"] = msg 
   this.Data["json"] = result
   this.ServeJSON
}

以上通过 GetSession 获取 session信息。 具体有关session的使用,参见 beego 中session module, Session control, 后者是对前者的包装。
该接口的访问路径为: /api/user/check (在router下配置,将该路径映射到函数Check())

2 nginx 端配置(在 外网服务器 A 上, 假定域名为: testapi.com)
        location  /api {
            add_header 'Access-Control-Allow-Origin' 'http://10.168.10.10:5500';
            add_header 'Access-Control-Allow-Credentials' 'true';
            proxy_pass   http://127.0.0.1:8080/api;
        }

3 js 请求(前端在局域网内的机器上,开发工具 visual studio code,)

    $.ajax({
        type:"GET",
        url: "http://testapi.com/api/rss/count",
        xhrFields: {
            withCredentials: true
         },
         crossDomain: true,
         success: function(resp){
            if(resp.returncode == 0)
            {
               alter("log in");
            } 
        }

    })

该机器 ip 假定为 10.168.10.10 (windows ipconfig 获取), 对应端口为 5500,该信息将在上面的nginx中使用。

跨域请求想要带上cookies必须在请求头里面加上用户凭证

{crossDomain: true, xhrFields: {withCredentials: true}}

设置。
由于是用 withCredentials, nginx端会要求是用指定的 Origin,即上面的nginx中的Origin不应该配置成:

add_header 'Access-Control-Allow-Origin' '*';

而是应该配置成:

add_header 'Access-Control-Allow-Origin' 'http://10.168.10.10:5500';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值