为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 中从 Back 发送 Cookie,这是一个 api 休息

在 Go 中从 Back 发送 Cookie,这是一个 api 休息

Go
POPMUISE 2022-06-27 10:52:49
大家好,我怀疑我正在学习 golang 以及如何构建和使用 API。我几乎在服务器端(Golang)完成了所有工作,在前端(React.Js)中,我可以使用 Axios 发出获取/发布请求以进行登录、注册、发布(该应用程序将成为一个论坛)。问题是当我想保护一些路由时,当我试图从服务器端设置 Cookie 时,前端会得到一个空 Cookie,但相反,我可以在前端设置一个 cookie。我应该在哪里创建和管理 cookie 和会话?我会让一些代码。戈朗:处理程序的标题:w.Header().Set("Content-type", "application/json")w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")w.Header().Set("Access-Control-Allow-Headers", "Content-Type")w.Header().Set("Access-Control-Allow-Credentials", "true")饼干去:func SetCookie (w http.ResponseWriter) {cookie := http.Cookie{    Name: "LoginCookie",    Value: "LoginCookieValue",    Path: "/",}http.SetCookie(w, &cookie)}服务器通过前端的 AJAX 请求(Axios)在浏览器中的 Cookie 响应:Cookie: {Name: "", Value: "", Path: "", Domain: "", Expires: "0001-01-01T00:00:00Z", …}但是使用 React 我可以创建一个 cookie 并在浏览器中查看:      setCookie() {    const cookieName = 'LoginCookie'    const cookieVal = uuidv4()    const cookies = new Cookies();    cookies.set(cookieName, cookieVal , { path: '/' });    console.log(cookies.get(cookieName));  }我该做什么?不管怎么说,还是要谢谢你。编辑:在这里,我让完整的 Axios 请求作为成员建议:   async submit (event) {var userLogin = {  email: this.state.email,  password: this.state.password}let axiosConfig = {  headers: {    'Content-Type': 'application/json'  }}   event.preventDefault();   await axios.post(`http://localhost:2000/users/sign-in/`, userLogin, axiosConfig,     {withCredentials: true})   .then(response => {       console.log(response)       console.log(response.data)       console.log(response.data.status)       console.log(response.data.cookie)       if (response.data.status === 200) {         this.setCookie()       }       this.clearFieldLogin()          }).catch(err => console.log(err))  }  clearFieldLogin(){    document.getElementById("formLogin").reset()  }
查看完整描述

2 回答

?
森林海

TA贡献2011条经验 获得超2个赞

您需要在后端设置 cookie 并在 react 中读取它,{ withCredentials: true }选项应该在 axiosConfig 对象中:


axiosConfig["withCredentials"] = true

await axios.post(

    `http://localhost:2000/users/sign-in/`,

     userLogin, 

     axiosConfig,

 )

你的错误代码:


await axios.post(

   `http://localhost:2000/users/sign-in/`,

    userLogin, 

    axiosConfig,

    {withCredentials: true}

)


查看完整回答
反对 回复 2022-06-27
?
UYOU

TA贡献1878条经验 获得超4个赞

我应该建议检查您的 AJAX 请求代码。我认为您在向服务器端发送请求的配置有误。


你有withCredentials: true选择吗?


其次,您可以尝试设置Expires为您的服务器端 Cookie 对象。


expiration := time.Now().Add(365 * 24 * time.Hour)

cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}

http.SetCookie(w, &cookie)


查看完整回答
反对 回复 2022-06-27
  • 2 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号