从Apache2中运行的Angular向spring引导api发送请求时未找到java 404
我有一个带有spring boot后端api和Angular10前端的应用程序。当在本地运行这些时,我没有任何问题,并且一切运行正常。我已经在Debian VPS上部署了我的应用程序,Angular构建运行在apache2上。但是当我尝试发送请求时,我得到了一个402未找到请求的URL
在Apache中,我配置了一个反向代理来访问spring boot:
<VirtualHost *:80>
DocumentRoot /var/www/html
ProxyPass /api/ http://localhost:8080/
ProxyPassReverse /api/ http://37.128.150.186/api/
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
在我的环境中。在Angular I中,ts文件指定了url的基地址,如“/api/”,因此每个请求都将通过这些url通过Apache的基端口(:80)发送。但当我这么做的时候,我发现一个404没有找到。但是当我在URL中转到/api/时,我确实看到了SpringBoot的“主控制器”
尝试向spring引导控制器发送post时,在浏览器中请求:
Request URL: http://37.128.150.186/api/users
Request Method: POST
Status Code: 404
Remote Address: 37.128.150.186:80
Referrer Policy: strict-origin-when-cross-origin
错误响应:
"timestamp": "2021-05-02T21:15:46.970+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "//users"
在本例中,我尝试向其发送请求的控制器:
@RestController
@RequestMapping(value = "/api/users", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {
private final UserService userService;
private final PasswordEncoder encoder;
public UserController(final UserService userService, final PasswordEncoder encoder) {
this.userService = userService;
this.encoder = encoder;
}
@GetMapping
public ResponseEntity<List<UserDTO>> getAllUsers() {
return ResponseEntity.ok(userService.findAll());
}
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable final Long id) {
return ResponseEntity.ok(userService.get(id));
}
/**
*
* @param userDTO user type to create new user
* @return user written to the database
*/
@PostMapping
public ResponseEntity<Long> createUser(@RequestBody @Valid final UserDTO userDTO) {
// create new user
UserDTO newUser = new UserDTO();
// set email
newUser.setEmail(userDTO.getEmail());
// set firstname
newUser.setFirstName(userDTO.getFirstName());
// set lastname
newUser.setLastName(userDTO.getLastName());
// set hashed password
newUser.setPassword(encoder.encode(userDTO.getPassword()));
// return new user with hashed password
return new ResponseEntity<>(userService.create(newUser), HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<Void> updateUser(@PathVariable final Long id,
@RequestBody @Valid final UserDTO userDTO) {
userService.update(id, userDTO);
return ResponseEntity.ok().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable final Long id) {
userService.delete(id);
return ResponseEntity.noContent().build();
}
}
同样,当我在本地计算机上运行应用程序时,一切正常。我忘记配置什么了吗
# 1 楼答案
错误来自spring本身。 我认为错误在于您在一个概要文件中配置了上下文路径,但在另一个概要文件中没有配置。(如果你点击http://37.128.150.186/api/api/users,你会得到一个响应)
可能也是一个问题的是
ProxyPassReverse /api/ http://37.128.150.186/api/
我不确定是否需要将/api/附加到IP# 2 楼答案
如果没有@Autowired或@Inject注释,则无法添加构造函数参数
会是那样的view reference link
或