Angular 8应用程序部署在get,put,post,补丁程序中的NGINX上不起作用



docker上的nginx中部署的角应用程序不与Java后端API连接。获取方法返回html而不是对象,张贴,put,patch的405不允许

我已经使用了带有后端API的Angular *应用程序(Java Spring Boot(。在IDE中运行的Angular App已经与proxy.conf.json合作,并与Chrome cors一起通过任何后端请求。当我在Docker中将Angular App(尝试的1.15.0、1.16.0、1.17.0(上部署时开始问题。http.client操作都不想起作用。获取返回HTTP代码,而不是JSON/JAVASCRIPT-OBJECT。张贴,补丁,不允许返回405。

对我来说似乎是不适当的Nginx配置的问题,但另一方面,我测试了很多反向曲线和CORS配置,结果相同...

Angular App:http://localhost:8100(从Docker运行(Spring Boot API:http://localhost:8081(从IDE运行(

命令的角度构建:

ng build --prod

dockerfile:

FROM nginx:1.17.0
COPY nginx.conf /etc/nginx/nginx.conf
COPY prm-web-app/ usr/share/nginx/html/
EXPOSE 8100

nginx.conf:

http {
    include       mime.types;
    default_type  application/json;
    sendfile        on;
    keepalive_timeout  65;
    upstream api_server {
        server localhost:8081;
    }
    server {
        listen       8100;
        server_name example;
        index index.html index.htm;
        root /usr/share/nginx/html;
        location / {
          add_header Allow 'GET, POST, PUT, PATCH, DELETE' always;
          add_header 'Access-Control-Allow-Origin' '*' always;
          add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, PATCH, DELETE, OPTIONS' always;
          add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
          add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
          add_header 'Access-Control-Allow-Credentials' 'true' always;
          try_files $uri $uri/ /index.html;
        }
        location /api {
            add_header Allow 'GET, POST, PUT, PATCH, DELETE' always;
            proxy_pass http://api_server;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
            proxy_redirect off;
            proxy_set_header Host $http_host;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }        
    }
}

Angular Extras示例:

private extractData(res: Response) {
    const body = res;
    return body || { };
  }
private httpHeaders = new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Origin, X-Request-With, Content-type, Accept, X-Access-Token',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, OPTIONS'
  });

角示例获取操作:

getAppointment(id: string): Observable<any> {
    return this.http.get(apiEndpoint + '/' + id).pipe(
      map(this.extractData),
      catchError( err => {
        this.logger.logError(ErrorLevel.ERROR, JSON.stringify(err));
        err = this.handleError(err);
        return throwError(err);
      })
    );

角示例术后操作:

postSearchTimeSlot(searchTimeSlotPostRequest: SearchTimeSlotPostRequest): Observable<any> {
    const options = {headers: this.httpHeaders};
    return this.http.post(searchTimeSlotEndpoint + '/', searchTimeSlotPostRequest, options).pipe(
      map(this.extractData),
      catchError(err => {
        this.logger.logError(ErrorLevel.ERROR, JSON.stringify(err));
        err = this.handleError(err);
        return throwError(err);
      })
    );
  }

我尝试了以下解决方案:

error_page 405 =200 $uri;

和:

error_page 405 = @app;
location @app {
proxy_pass http://localhost:8081/api;
}

和:将应用程序/json添加到mime..types和:

const options = {headers: this.httpHeaders, responseType: 'json' as 'json'};
const options = {headers: this.httpHeaders, responseType: 'text' as 'json'};

和:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Bean
    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("PUT", "POST", "PATCH", "GET")
                        .allowCredentials(true).maxAge(3600);
            }
        };
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

和proxy_pass和add_header for nginx的其他几个。现在我已经缺乏想法...

每次都有相同的问题(对最新的Chrome和Mozilla Firefox进行了测试(:为了获得请求:

{
"headers": {
"normalizedNames": {},
"lazyUpdate": null
},
"status": 200,
"statusText": "OK",
"url": "http://localhost:8100/appointment_api/api/v1/appointment/123412341234",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure during parsing for http://localhost:8100/appointment_api/api/v1/appointment/123412341234",
"error": {
"error": {},
"text": "<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Example</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.ab8e79b2d91e978b1e50.css"></head>
<body>
    <app-root></app-root>
<script src="runtime-es2015.858f8dd898b75fe86926.js" type="module"></script><script src="polyfills-es2015.b8312458afdf3a7f4969.js" type="module"></script><script src="runtime-es5.741402d1d47331ce975c.js" nomodule></script><script src="polyfills-es5.8de8aa8baf008bce96d4.js" nomodule></script><script src="scripts.99edbfa41b8b40270fe5.js"></script><script src="main-es2015.49e5dbe84808fb269a5d.js" type="module"></script><script src="main-es5.628bd9db49e6b16c7a86.js" nomodule></script></body>
</html>
"
}
}

浏览器中的上述错误代码是因为Angular Expect JSON默认为JSON,但Nginx返回JSON的HTML Instad。

用于put,发布,补丁请求:

"status": 405,
"statusText": "Not Allowed",
"url": "http://localhost:8100/appointment_api/api/v1/searchTimeSlot/",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for http://localhost:8100/appointment_api/api/v1/searchTimeSlot/: 405 Not Allowed",
"error": "<html>
<head><title>405 Not Allowed</title></head>
<body>
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx/1.17.0</center>
</body>
</html>

对于这两个问题

解决了问题。

是docker阻止了从nginx到API的流量 - (我正在测试NGINX上的Dockerized Angular,但API直接从IDE运行。

解决方案是创建Docker组成的,该码头将在一个Docker网络中组合所有必要的模块(API和前端(,或(就像我一样(直接在Kubernetes上部署并配置服务。

最新更新