【问题标题】:Spring boot & maven: use custom url path for backend results in whitelabel errorSpring boot & maven:对后端使用自定义 url 路径导致白标签错误
【发布时间】:2021-07-12 12:56:35
【问题描述】:

我有两个单独的项目,一个 projectApi(弹簧后端)和一个 projectUi(角度前端)。 我正在使用 maven-resource-plugin 将它们组合到一个 jar 中进行生产。 当我启动 spring 服务器时,这两个模块之间的连接工作正常。

现在我想自定义后端 url 路径,以便像 'http://localhost:8088/login' 这样的请求看起来像 'http://localhost:8088 /api/v1/登录。

我可以通过将以下条目添加到 application.properties:spring.mvc.servlet-path=/api/v1 并修改基本 url 来实现从 ui 到 api 的调用。

由于该更改,我在调用 ui (localhost:8088) 时遇到了白标签错误。 经过一番搜索,我尝试实现WebMvcConfigurer,但它对我不起作用。这是参考stackoverflow link

// Application.java

@SpringBootApplication
@EnableJpaRepositories
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


// UserRestService.java

@RestController
@RequestMapping("/user")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UserRestService extends AbstractRestService {
  ...
  @PostMapping("/login")
    public String login(@RequestBody User user) throws CustomException {
        return Response.ok(userService.loginUser(user, response));
    }
}



// application.properties

server.port=8088

// without that entry the post request works fine -> localhost:8088/user/login
// adding that entry and trying to call: localhost:8088/api/v1/user/login i get whitelabel error
spring.mvc.servlet.path=/api/v1

【问题讨论】:

  • 看不到你的代码就帮不上忙。
  • @Shubh 我给你添加了一些代码,不确定你想要/需要看到什么。我唯一改变的是 application.properties 文件中的这一行和前端使用的 base-url。也许你知道完全不同的方式,我怎样才能达到我的目标。我想访问地址为 localhost:8088/... 的前端和地址为 localhost:8088/api/v1/...的后端 谢谢

标签: java angular spring spring-boot


【解决方案1】:

尝试将“/api/v1/”添加到您的控制器,否则您的所有控制器都将以该路径为前缀,您将无法提供具有相同应用程序的其他版本。

【讨论】:

    【解决方案2】:

    我更喜欢编程到接口。这有助于更好地利用 IOC。将 URI 前缀 (/api/v1/) 添加到如下界面。它会将此前缀附加到接口提供的所有方法中。

    // Interface for UserRestService with URI prefix mentioned using Request mapping annotation
    @RequestMapping(value = "/api/certs/", produces = { "application/json" },consumes = { "application/json" })
    public interface IUserRestService {
      String login(User user) throws CustomException;
    }
    
    //UserRestService Class 
    @RestController
    @RequestMapping("/user", method = RequestMethod.POST)
    public class UserRestService extends AbstractRestService implements IUserRestService{
      ...
      @PostMapping("/login")
        public String login(@RequestBody User user) throws CustomException {
            return Response.ok(userService.loginUser(user, response));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-26
      • 2020-06-22
      • 1970-01-01
      相关资源
      最近更新 更多