【发布时间】:2020-08-23 22:05:05
【问题描述】:
大家好,我怀疑我正在学习 golang 以及如何构建和使用 API。我几乎在服务器端 (Golang) 上完成了所有工作,在前端 (React.Js) 中,我可以使用 Axios 发出获取/发布请求以进行登录、注册、发布(该应用程序将成为一个论坛)。问题是当我想保护一些路由时,当我试图从服务器端设置 Cookie 时,前端会得到一个空的 Cookie,但相反,我可以在前端设置一个 cookie。我应该在哪里创建和管理 cookie 和会话?
我会放一些代码。
Golang:
处理程序的标头:
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 Request(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()
}
【问题讨论】:
-
不,彼得,我在发布我的问题之前看到了那个帖子。
-
你应该为
fetch使用credentials: 'include'选项 -
我正在使用 Axios,我应该使用 fetch 吗?我必须在哪里放置凭据:'include'
-
哦,不好意思,我以为你在使用 fetch。
标签: reactjs http go cookies axios