gpt4 book ai didi

angular - 将 Angular 表单提交到 Go API 不断发布 Nil

转载 作者:数据小太阳 更新时间:2023-10-29 03:20:15 26 4
gpt4 key购买 nike

我正在尝试从我的 Angular 前端向我的 Go API 发送消息,但无论我做什么,它都会向 Go API 发送 nil。当我测试变量是否发送到 Angular 订阅者时,它显示它们是,但由于某种原因它不会发布到这个简单的 Go 端点

这是我的代码,如有任何帮助,我们将不胜感激:

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 订阅者

 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;
}));
}

这是我在 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 []}

然后我在 Angular 中收到一个 CORS 错误,它是:

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.

如果有人能帮助我,我将不胜感激。我是 Go 和 Angular 的新手,并且仍在学习如何让它们相互交互。

最佳答案

像这样进行更改:

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 客户端

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;
}));
}

关于angular - 将 Angular 表单提交到 Go API 不断发布 Nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55134767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com