douluohan3403 2018-12-17 11:28
浏览 61
已采纳

为什么我无法获得Angular的体形

I use angular to get information register html and I post to path api it work but print word "work" and I cant not get value In body and I test path post use postman it show firstname.......................................................................................................................................

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

register.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)
 
    }
}

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

  }
}

</div>
  • 写回答

1条回答 默认 最新

  • dpxbc88022 2018-12-17 11:43
    关注

    I think it could be that your go server is expecting a content-type: application/x-www-form-urlencoded

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

    But angular is submitting the form as a json object.

    To debug what is happening check the outgoing response from chrome to your backend Do this by enabling "Log XmlHttpRequest from the settings menu in chrome devtools.

    You should then be able to se that the body is JSON.

    Try using this to parse the body instead

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊