我正在使用 Angular 12 CLI 和 Spring Boot 2.5.5。使用 Angular 服務,我嘗試使用 POST http 請求將 JSON 從組件傳遞到 Spring Boot。JSON 到達 Spring Boot 后,我??需要在控制臺中列印它,但我無法讓它作業。使用 Postman,我正確地可視化了 JSON,所以我認為問題出在前端。這是一些代碼:
用戶服務.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from 'src/user';
@Injectable({
providedIn: 'root'
})
export class UsersService {
constructor(private http: HttpClient) { }
getUsers(): Observable<User[]>{
return this.http.get<User[]>("http://localhost:8080/user/all")
}
addNewUser(user: User): void {
const httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'application/json' }
)
};
let userJSON = JSON.stringify(user);
this.http.post("http://localhost:8080/user/add", userJSON, httpOptions);
}
}
用戶控制器
package com.sporthub.backend.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sporthub.backend.model.Role;
import com.sporthub.backend.model.User;
import com.sporthub.backend.repository.RoleRepository;
import com.sporthub.backend.repository.UserRepository;
@Controller
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepo;
@Autowired
private RoleRepository roleRepo;
@GetMapping("/all")
public @ResponseBody Iterable<User> getUsers(){
return userRepo.findAll();
}
@PostMapping("/add")
public @ResponseBody String addUser(@RequestBody String user) {
System.out.println(user);
return user;
}
}
HTML 表單
<form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()">
<div>
<label for="name">
Name
</label>
<input type="text" id="name" formControlName="name">
</div>
<div>
<label for="lastname">
lastname
</label>
<input type="text" id="lastname" formControlName="lastname">
</div>
<input type="submit" value="Add new user">
</form>
用戶組件
import { Component, OnInit } from '@angular/core';
import { User } from 'src/user';
import { UsersService } from '../users.service';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
users : User[] = [];
checkoutForm = this.formBuilder.group({
name: '',
lastname: ''
});
constructor(
private usersService: UsersService,
private formBuilder: FormBuilder
) { }
onSubmit(): void {
let name = this.checkoutForm.get('name')?.value;
let lastname = this.checkoutForm.get('lastname')?.value;
let user: User = {
"name": name,
"lastname": lastname
};
console.log(user);
this.usersService.addNewUser(user);
}
ngOnInit(): void {
this.getUtenti();
console.log(this.users);
}
getUsers() : void{
this.usersService.getUsers().subscribe(users => this.users = users);
}
}
uj5u.com熱心網友回復:
您在客戶端的網路服務中添加了一個 Content Type 標頭,但沒有告訴您的后端。
我認為您應該將您的@PostMapping方法重構為:
@PostMapping(path = "/add", produces = MediaType.APPLICATION_JSON_VALUE) // <- here
public @ResponseBody String addUser(@RequestBody String user) {
System.out.println(user);
return user;
}
或者,您可以將其添加到@RequestMapping,以便它適用于所有控制器的方法。
順便說一句:您回傳的是 String 而不是物件(將被決議為 json)
所以我建議你改變你的@RequestBody String userto@RequestBody YourUserDtoBackendType user并直接在 webservice 的客戶端主體中洗掉JSON.stringify(user)并傳遞 a user,然后序列化/反序列化應該通過Jackson(Spring Boot 為其提供內置支持)自動執行
uj5u.com熱心網友回復:
編輯:解決了。
在我的 UsersService 中使用 Observable 作為我的 addNewUser 函式的回傳型別
addNewUser(user: User): Observable<User> {
return this.http.post<User>("http://localhost:8080/user/add", user, this.httpOptions);
}
然后我在組件內的 onSubmit() 函式中添加了一個.subscribe()方法。
this.usersService.addNewUser(user).subscribe(user => console.log(user));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339583.html
下一篇:小專案的側邊欄結構
