为什么我无法获得body形态 角度



我使用angular获取信息寄存器html,并将其发布到路径api,它可以工作,但打印单词"work",我无法获取值在body中,我测试路径后使用邮递员显示名字。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

server.go

package main
import (
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
	"net/http"
)
func main() {
	router := mux.NewRouter()
	router.HandleFunc("/register", Createuser).Methods("POST")
	headers := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"})
	methods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE"})
	origins := handlers.AllowedOrigins([]string{"*"})
	http.ListenAndServe(":12345", handlers.CORS(headers, methods, origins)(router))
}
func Createuser(writer http.ResponseWriter, request *http.Request) {
	request.ParseForm()
print(request.FormValue("firstName"))
	print("work")
}

寄存器.组件.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { AlertService, UserService } from '../_services';
@Component({templateUrl: 'register.component.html'})
export class RegisterComponent implements OnInit {
registerForm: FormGroup;
loading = false;
submitted = false;
constructor(
private formBuilder: FormBuilder,
private router: Router,
private userService: UserService,
private alertService: AlertService) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
username: ['', Validators.required],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
this.loading = true;
this.userService.register(this.registerForm.value)

}
}
user.service.ts

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {environment} from '../../environments/environment';
import {User} from '../_models';
@Injectable()
export class UserService {
constructor(private http: HttpClient) {
}
register(user: User) {
return this.http.post(`${environment.apiUrl}/register`, {
firstName: user.firstName,
lastName : user.lastName,
username : user.username,
password : user.password
})
}
}
}

我认为您的go服务器可能正在等待content-type: application/x-www-form-urlencoded

https://golang.org/pkg/net/http/#Request.ParseForm

但是angular将表单作为json对象提交。

要调试正在发生的事情,请检查从chrome到后端的传出响应要做到这一点,请在chrome devtools.中启用"从设置菜单记录XmlHttpRequest">

然后,您应该能够确定主体是JSON。

尝试使用它来解析正文,而不是

func test(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var t test_struct
err := decoder.Decode(&t)
if err != nil {
panic(err)
}
log.Println(t.Test)
}

最新更新