dongze5043
2018-07-23 05:58
浏览 51

jQuery Ajax不创建golang会话cookie

I am creating an creating login part for with preact, jquery and golang. I am using chrome for testing. The login API works fine with testing by postman written in golang. Here is code for this part

e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))
//e.Use(xrayWrapper("bonusapi"))

e.POST("/login", func(c echo.Context) error {
    sess, _ := session.Get("session", c)
    sess.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   86400 * 7,
        HttpOnly: true,
    }

    if(sess.Values["auth"] == true){
        return c.String(http.StatusOK, "Already Login")
    }else {
        fmt.Println(sess.Values["auth"])
    }

    if(c.FormValue("password") == "admin" && c.FormValue("username") == "admin"){
        sess.Values["auth"] = true
        sess.Save(c.Request(), c.Response())
        fmt.Println(sess.Values["auth"])
        return c.String(http.StatusOK, "Login session start")
    }else {
        return c.String(http.StatusOK, "Forbidden Access")
    }

    //return c.String(http.StatusOK, )
})

But it does not work when I use ajax request with jquery. I mean session cookies does do not work in ajax request. I am not sure what is the problem with it. Anyone can help, please. Here is my ajax request code which has a problem I think

var username = props["path"][6].getElementById("username").value.trim();
    var password = props["path"][6].getElementById("password").value.trim();
    var credentials = {
        username: username,
        password: password
    }

    var _this = this
    $.ajax({
        type: "POST",
        url:"http://127.0.0.1:5000/login", 
        data:credentials
    })
    .done(function(data){
        console.log(data);
    });
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzi0609 2018-07-23 06:31
    已采纳

    You're missing ajax headers withCredentials

    For cross-domain scenario, 3 things need to happen:

    • Client needs to set withCredentials=true for the xhr object
    • Set Access-Control-Allow-Credentials both in the OPTIONS preflight request as well as the actual request
    • Set the cookie as needed

    The most interesting capability exposed by both XMLHttpRequest or Fetch and CORS is the ability to make "credentialed" requests that are aware of HTTP cookies and HTTP Authentication information. By default, in cross-site XMLHttpRequest or Fetch invocations, browsers will not send credentials.

    $.ajax({
        type: "POST",
        url:"http://127.0.0.1:5000/login", 
        data:credentials,
        xhrFields: {
          withCredentials: true
       }
    })
    .done(function(data){
        console.log(data);
    });
    
    点赞 评论

相关推荐 更多相似问题