angular - 为什么我无法获得体形 Angular

标签 angular api go http-post

我使用 angular 来获取信息注册 html 并且我发布到路径 api 它工作但打印单词“工作”并且我无法在正文中获得值(value)并且我测试路径后使用 postman 显示名字................................................................ ..................................................... ............................................

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

注册.component.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)
 
    }
}
用户服务.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 的设置菜单中启用“Log 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)
}

关于angular - 为什么我无法获得体形 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53814304/

相关文章:

部署到 Springboot 应用程序后,Angular 路由不起作用

api - 在 .net Core Api 中创建用于授权的自定义操作过滤器

go - 通过读取 .go 文件来反射(reflection)结构类型

git - 如何指定 `go get` 将使用哪个 ssh key

go - 在golang中打开一个url并读取重定向的url

javascript - Angular 5 所需的表单字段不适用于 Material

css - 如何调整 Angular Material 组件的大小

angular - 如何在 Angular 2 中将组件设置回初始状态

node.js - 尝试从 api 获取 token 时 Node 获取的错误行为

REST:长时间运行操作中处理错误,如何通知客户端?