go+cookie+angular踩过的坑

出现问题

  • go后端在设置路由的时候,响应头设置带有cookie。但是angular向该接口发起post请求的时候,返回的数据没有cookie

原因和解决办法

  • cookie在跨域请求的时候,会丢失。因此我们在angular项目中设置代理

解决

  • go后端代码

    • 后端功能:接收angular向SetCookie接口发起的post请求数据,将该数据转化为cookie值
    package main
    
    import (
    
    ​    "net/http"
    
    ​    "io/ioutil"
    
    ​    "encoding/json"
    
    ​    "fmt"
    
    )
    
    
    type UpLoadMes struct{
    
    ​    Text string
    
    ​    Picture []string
    
    }
    
    
    type Login struct {
    
    ​    Name string `json:"name"`
    
    ​    Num string `json:"num"`
    
    }
    
    
    
    func main(){
    
    ​    fmt.Println("正在监听8080......")
    
    ​    http.HandleFunc("/SetCookie",SetCookie)
    
    ​    http.ListenAndServe(":8080",nil)
    
    }
    
    
    func SetCookie(w http.ResponseWriter, r *http.Request){
    
    ​    if r.Method!="POST"{
    
    ​        fmt.Println(r.Method)
    
    ​        return
    
    ​    }
    
    ​    w.Header().Set("Access-Control-Allow-Origin", "*")
    
    ​    w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
    
    ​    w.Header().Set("content-type", "application/json")
    
    ​    w.Header().Set("content-type", "application/x-www-form-urlencoded")
    
    ​    body,err:=ioutil.ReadAll(r.Body)
    
    ​    defer r.Body.Close()
    
    ​    if err!=nil{
    
    ​        panic(err)
    
    ​    }
    
    ​    var loginData Login
    
    ​    err=json.Unmarshal(body,&loginData)
    
    ​    if err!=nil{
    
    ​        panic(err)
    
    ​    }
    
    ​    fmt.Println(loginData)
    
    ​    cookie := http.Cookie{Name: loginData.Name, Value:loginData.Num, MaxAge: 60}
         //MaxAge表示cookie能存活的时间
    
    ​    w.Header().Set("Set-Cookie",cookie.String())
    
    ​    data := make(map[string]string)
    
    ​    data["name"] = loginData.Name
    
    ​    json,err := json.Marshal(data)
    
    ​    if err!=nil{
    
    ​        panic(err)
    
    ​    }
    
    ​    w.Write(json)
    
    }
    
  • angular项目中设置代理

    • 在项目生成名字为proxy.conf.json的代理文件

  • 在该文件写入

    {
        "/test":{
            "target":"http://localhost:8080",
            "sercure":false,
            "logLevel":"debug",
            "changeOrigin":true,
            "pathRewrite":{
                "^/test":""
            }
        }
    }
    
  • 在angular.json文件中写入

  • angular发起请求部分

      loginSubmit(name:string,num:string){
        if(name==null||name==undefined){
          console.error("onSubmit name有误")
          return
        }
        if(num==null||num==undefined){
          console.error("onSubmit num有误")
          return
        }
        if(name==""&&num==""){
          console.error("name and num 都是空的")
          return
        }
        var httpOptions={
          headers:new HttpHeaders({'content-Type':'application/x-www-form-urlencoded'}),
        }
        var api="/test/SetCookie"
        // /test/SetCookie 相当于 http://localhost:8080//SetCookie
        return this.http.post(api,{"name":name,"num":num},httpOptions).pipe(
          catchError(this.handleError)
        )
      }
    

注意

  • 根据上面设计之后,在cookie的有效期内,angular发起的大部分的请求都会带上cookie
原文地址:https://www.cnblogs.com/MyUniverse/p/11496571.html