【问题标题】:angular proxy issues getting index.html or cors error角度代理问题得到 index.html 或 cors 错误
【发布时间】:2019-04-17 20:51:25
【问题描述】:

大家好,我的 Angular 客户端有一些问题。 每当我使用这样的代理向我的 Spring 后端发出发布请求时......

{
   "/api": { 
      "target": "http://localhost:3000", 
      "secure": false, 
      "changeOrigin": true,
      "pathRewrite": {
          "^/api": "" 
       }
   }
}

如果我将 changeOrigin 设置为 False,那么它可以按预期在后端运行。登录效果很好。唯一奇怪的是角度客户端的响应。我没有从后端服务器获取原始响应,而是获取了我的角度应用程序的 index.html 文件的内容。 httpClient.post.subscribe(...) 中的响应只是 Index.html 文件的内容。

然后我尝试将 changeOrigin 设置为 true。但后来什么都没有了。 我收到一个 cors 错误,我的 Spring Backend 拒绝了该请求。为什么? 我想当我希望在后端禁用 cors 时,使用代理是可行的方法。至少在设置开发环境方面是这样。

在后端,我的 Spring Security 看起来像这样:

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().exceptionHandling()
            .authenticationEntryPoint(
                    (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED)
            )
            .and().authorizeRequests()
            .antMatchers("/login", "/authorize").permitAll()
            .anyRequest().authenticated()
            .and().formLogin().permitAll();//.and().httpBasic();

}

在我的浏览器中,客户端向我显示以下错误消息:

【问题讨论】:

  • 试试"logLevel": "debug",看看它是否有助于弄清楚发生了什么
  • 另外,当您向后端发出请求时,URL 是 http://localhost:4200/api/... 对吧?
  • 是的请求将发送到localhost:4200/api/login 一个帖子请求例如
  • 我已经打开了调试模式。它表示请求已正确转发到后端。甚至显示它的后端。唯一的错误消息是在我的浏览器中缺少访问控制源标头。
  • 所以当您的前端在localhost:4200 和您的后端提供服务时,您收到有关访问控制来源的错误消息?

标签: spring angular proxy cors


【解决方案1】:

为了解决我的问题,我在后端激活了跨源令牌。

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

我认为如果我使用代理就没有必要了。

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 2020-12-01
    • 2015-10-27
    • 2016-10-05
    • 2019-09-06
    • 2015-02-20
    • 2020-05-31
    • 2020-03-02
    • 2018-03-19
    相关资源
    最近更新 更多