Angular前端注册表单提交数据,SpringBoot后端未接收问题求助
Angular前端提交注册数据到SpringBoot后端失败,Postman测试正常
开发在线考试门户,前端采用Angular,后端使用SpringBoot,数据库为MySQL。后端新增用户接口通过Postman测试验证可用,但前端注册表单提交数据时,后端无法接收数据,控制台出现错误。
环境信息
- Apache Tomcat Server运行在8080端口
- Angular开发服务器运行在4200端口
相关情况说明
- 控制台显示请求相关错误(如地址无效、CORS异常)
- Postman发送POST请求到
/user/接口成功,数据库Users表数据更新正常 - 前端文件层级包含app/components/signup、app/services等目录
- 后端文件层级包含com.exam.controller、com.exam.entity、com.exam.services等目录
前端代码
signup.component.ts
import { Component, OnInit } from '@angular/core'; import { UserService } from 'src/app/services/user.service'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.css'] }) export class SignupComponent implements OnInit { constructor(private userService:UserService){} public user={ username:'', password:'', firstname:'', lastname:'', email:'', mobile:'' } ngOnInit():void{} formSubmit(){ console.log(this.user); if(this.user.username == '' || this.user.username == null){ alert('User Name Field cannot be blank!'); return; } //addUser:UserService this.userService.addUser(this.user).subscribe( { next: (data) => console.log(data), error: (err) => console.log(err), complete: () => console.log("completed") }); } }
helper.ts
let baseUrl="http//:localhost:8080" export default baseUrl
user.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http:HttpClient) { } public addUser (user:any){ return this.http.post('${baseUrl}/user/',user); } }
后端代码
UserController.java
package com.exam.controller; import com.exam.entity.Role; import com.exam.entity.User; import com.exam.entity.UserRole; import com.exam.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.HashSet; import java.util.Set; @CrossOrigin(allowCredentials = "") @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; //create user @PostMapping("/") public User createUser(@RequestBody User user) throws Exception { Role role = new Role(); role.setRoleID(191001001105L); //Default role id set role.setRoleName("NORMAL"); UserRole userRole= new UserRole(); userRole.setUser(user); userRole.setRole(role); Set<UserRole> roles= new HashSet<>(); roles.add(userRole); return this.userService.createUser(user,roles); } //get user by username @GetMapping("/{username}") public User getUser(@PathVariable("username") String username){ return this.userService.getUser(username); } //delete user by Id @DeleteMapping("/{userId}") public void deleteUser(@PathVariable("userId") Long userId){ this.userService.deleteUser(userId); } }
解决方案
1. 修正前端URL配置错误
- helper.ts:URL格式错误,
http//:localhost:8080应改为http://localhost:8080let baseUrl="http://localhost:8080" export default baseUrl - user.service.ts:
- 缺少baseUrl的导入语句,需根据实际路径导入
- 字符串模板需用反引号
`包裹,而非单引号
修改后代码:
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import baseUrl from '../helper'; // 根据helper.ts的实际位置调整路径 @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http:HttpClient) { } public addUser (user:any){ return this.http.post(`${baseUrl}/user/`, user); } }
2. 修正后端CORS配置
@CrossOrigin(allowCredentials = "")配置无效,需指定允许的前端源并正确设置跨域参数:
@CrossOrigin(origins = "http://localhost:4200", allowCredentials = true) @RestController @RequestMapping("/user") public class UserController { // ... 其余代码不变 }
完成以上修改后,重新启动前后端服务,测试注册表单提交即可正常请求后端接口。
内容的提问来源于stack exchange,提问作者Mainak Shaw
相关产品推荐
相关产品推荐

