Div*_*arg 5 java spring-boot angular
我正在开发一个前端为 angular 6,后端为 spring boot 的应用程序。在实现用户身份验证模块时,我想相应地在登录后重定向到学生和教职员工的家。
但是,我无法从 Spring Boot 重定向页面。在 Spring MVC 中使用从控制器操作重定向到外部 URL这个解决方案我收到 CORS 错误:“在预检响应中访问控制允许头不允许请求头字段内容类型。”
或者,如果有另一种方法来完成这项任务?
认证控制器.java
package sgsits.cse.dis.user.controller;
@CrossOrigin(origins = "*") // enables cross origin request
@RestController
@RequestMapping(value = "/dis")
@Api(value = "Authentication Resource")
public class AuthenticationController {
@Autowired
StudentRepository studRepo;
@Autowired
StaffRepository staffRepo;
@Autowired
EmailController email;
String pattern = "MM-dd-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
@ApiOperation(value = "login", response = Object.class, httpMethod = "POST", produces = "application/json")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestBody Authentication auth, HttpServletResponse httpServletResponse) {
Optional<StaffProfile> staff = staffRepo.findByEmail(auth.getUsername());
if (staff.isPresent()) {
String md5_pass = MD5.getHash(auth.getPassword());
if (staff.get().getPassword().equals(md5_pass)) {
// set session
// update last login
return "forward:/localhost:4200/staff";
} else
return "You have entered incorrect password";
} else {
Optional<StudentProfile> student = studRepo.findByEnrollmentId(auth.getUsername());
if (student.isPresent()) {
String md5_pass = MD5.getHash(auth.getPassword());
if (student.get().getPassword().equals(md5_pass)) {
// set session
// update last login
httpServletResponse.setHeader("Location", "http://localhost:4200/reset-password");
httpServletResponse.setStatus(302);
return "redirect:localhost:4200/student";
} else
return "You have entered incorrect password";
} else {
return "You are not registered with the system. Please signup first";
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 3
不要@CrossOrigin(origins = "*")向控制器添加注释。
假设您的 api 在 8080 上运行,而您的角度代码在 4200 上运行。
创建一个名为 proxy.conf.json 的文件
{
"/api/": {
"target": "http://localhost:8080/",
"secure": false,
"changeOrigin": true
}
Run Code Online (Sandbox Code Playgroud)
使用此命令启动角度应用程序
ng服务--proxy-config proxy.conf.json
使用此配置,当您调用 localhost:4200/api 时,它将调用 8080 并且不会出现任何 CORS 错误
| 归档时间: |
|
| 查看次数: |
5113 次 |
| 最近记录: |