dpxua26604 2019-03-13 05:08
浏览 78

将Angular表单提交到Go API会持续发布Nil

I am trying to post from my angular frontend to my Go API and no matter what I do it keeps posting nil to the Go API. When I test if the variables are making it to the Angular subscriber it shows that they are but for some reason it will not post to this simple Go endpoint

Here is my code any help would be very greatly appreciated:

GO API

package main

import (
    "encoding/json"
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "log"
    "net/http"
    "time"
)

func main() {

    http.HandleFunc("/signin", indexHandler)
    http.HandleFunc("/welcome", Welcome)
    http.HandleFunc("/refresh", Refresh)

    // start the server on port 8000
    log.Fatal(http.ListenAndServe(":8001", nil))
}

func setupResponse(w *http.ResponseWriter, req *http.Request) {
    (*w).Header().Set("Access-Control-Allow-Origin", "*")
    (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}

func indexHandler(w http.ResponseWriter, req *http.Request) {
    setupResponse(&w, req)
    if (*req).Method == "POST" {
        return
    }
    fmt.Println(req.Header)

    fmt.Println(req.ParseForm())
    fmt.Println(json.NewDecoder(req.Body))

}

Angular Subscriber

 login(username: string, password: string) {

    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json charset=utf-8'
        , 'Access-Control-Allow-Origin': '*'
        , 'Access-Control-Allow-Headers': 'access-control-allow-origin, access-control-allow-headers'})
    };
   return this.http.post(`${environment.APIEndpoint}/signin`, {username, password}, httpOptions).pipe(map(user => {
        // login successful if there's a jwt token in the response
        if (user && user) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
        }

        return user;
      }));
  }

This is my Output in Go

map[User-Agent:[Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Mobile Safari/537.36] Access-Control-Request-Headers:[access-control-allow-headers,access-control-allow-origin,content-type] Referer:[http://localhost:4200/login?returnUrl=%2Fdashboard] Accept-Language:[en-US,en;q=0.9] Connection:[keep-alive] Accept:[/] Accept-Encoding:[gzip, deflate, br] Access-Control-Request-Method:[POST] Origin:[http://localhost:4200]] &{{} [] {[] 0 { false [] false 0 0} { false [] false 0 0} { } false false} 0 0 { false [] false 0 0} 0 []}

And I am then getting a CORS error in Angular which is:

Access to XMLHttpRequest at 'http://localhost:8001/signin' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

I would be very grateful if anyone can help me. I am new to both Go and Angular and am still learning how to get them to interact with each other.

  • 写回答

1条回答 默认 最新

  • duanbei3747 2019-03-13 14:44
    关注

    make changes like so:

    func indexHandler(w http.ResponseWriter, req *http.Request) {
        setupResponse(&w, req)
        if (*req).Method == "POST" {
              fmt.Println(req.Header)
    
              fmt.Println(req.ParseForm())
              fmt.Println(json.NewDecoder(req.Body))
        }
    }
    

    Angular client side

    login(username: string, password: string) {
    
        const httpOptions = {
          headers: new HttpHeaders({ 'Content-Type': 'application/json charset=utf-8'})
        };
       return this.http.post(`${environment.APIEndpoint}/signin`, `{"username":username, "password":password}`, httpOptions).pipe(map(user => {
            // login successful if there's a jwt token in the response
            if (user && user) {
              // store user details and jwt token in local storage to keep user logged in between page refreshes
              localStorage.setItem('currentUser', JSON.stringify(user));
            }
    
            return user;
          }));
      }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助