【问题标题】:Problems accessing Spring-Boot RestController from Angular frontend从 Angular 前端访问 Spring-Boot RestController 的问题
【发布时间】:2019-05-11 20:09:19
【问题描述】:

我有以下设置:

我的控制器:

@RequestMapping("/project")
@RestController
public class ProjectController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ProjectService projectService;

    @CrossOrigin
    @PostMapping(value = "/createProject")
    public ResponseEntity createProject(@RequestBody ProjectDto projectJsonString) {
        return ResponseEntity.ok(HttpStatus.OK);
    }
}

在我的.service.ts

this.http.post('http://localhost:8080/project/createProject', JSON.stringify(project)).
      subscribe( (res) => {
        this.logger.info('Response: ' + res);
      });

我的 Dto:

public class ProjectDto {
    private String projectName;
    private String projectNumber;
    private String projectArea;
    private String managerName;
    private String managerShorthand;
}

但是当我将应用程序构建到 jar 文件并执行它时,执行 api-call 时出现以下错误:

HttpErrorResponse {headers: HttpHeaders, status: 415, statusText: "OK", url: "http://localhost:8080/project/createProject", ok: false, …}
error:
error: "Unsupported Media Type"
message: "Content type 'text/plain;charset=UTF-8' not supported"
path: "/project/createProject"
status: 415
timestamp: "2018-12-10T21:41:26.036+0000"

当我curl 它时也会发生同样的事情。谁能告诉我我做错了什么?

【问题讨论】:

  • 网址中的“createProject”是什么?我没有看到映射。只需使用localhost:8080/project
  • @Lemmy 对不起,我看到我的课程仍然包含该 url 的 const,我会更新它。这是我的方法的映射器 - 我看到了第一个问题,我使用 name 而不是 value,谢谢!
  • 我明白这一点,但我是说你没有 createProject 的映射。使用值而不是名称。见docs.spring.io/spring-framework/docs/current/javadoc-api/org/…
  • 删除 stringify 因为你必须发送 json

标签: angular maven spring-boot


【解决方案1】:

当请求不包含适当的 Content-Type 标头时,会出现“不支持的媒体类型”错误。

请确保您的请求包含值为“application/json”的“Content-Type”标头(假设您发送的数据是 Json)。

【讨论】:

    【解决方案2】:

    正如 HL'REB 所提到的,您应该将正确的 Content-Type 添加到您的发布请求中,因为您使用的是 spring boot 和 RestControllers 我假设默认的 json 支持已激活,所以这可能是预期的媒体类型(@987654321 @)。

    所以你可以尝试以下更改

    this.http.post('http://localhost:8080/project/createProject', JSON.stringify(project), 
    { 
      headers: {'Content-Type': 'application/json'} 
    }).subscribe( (res) => {this.logger.info('Response: ' + res);});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-21
      • 2019-06-06
      • 2022-10-23
      • 2018-03-18
      • 2019-04-02
      • 2020-09-08
      • 2019-01-24
      • 1970-01-01
      相关资源
      最近更新 更多