在NGINX反向代理后面部署Angular和Spring-boot应用程序

时间:2019-12-27 12:41:56

标签: angular spring-boot nginx cors reverse-proxy

这个想法是要设置一个NGINX反向代理来处理前端(Angular 5)和后端(Spring boot)之间的通信。前端应向REST API发出请求(aka。Spring启动应用程序)并显示响应。

配置

NGINX

NGINX配置为:

/etc/nginx/sites-enabled/app.conf

server {
    listen 80;
    #server_name www.servername.com
    location / {
        rewrite /(.*) /$1 break;
        proxy_pass         http://localhost:4200;
        #proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
        error_log         /var/log/nginx/seodwarfapp.error.log;
    }
    # spring-boot-app
    location /api {
        proxy_pass         http://localhost:8090;
        # proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
   }
}

/etc/nginx/nginx.conf

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 1024;
        # multi_accept on;
}

http {
        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;
        gzip_disable "msie6";

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

SPRING

将SPRING应用配置为允许来自http://localhost:4200的CORS。 控制器使用适当的注释:

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping(path = "/api")
public class QueryController {

    @Autowired
    private QueryManager queryManager;
    @Autowired
    private QueryBuilder queryBuilder;

    @PostMapping(path = "/query", consumes = "application/json")
    public String constructSparqlQuery(@RequestBody SparqlRequest request) {
        String results = "";
        String sparqlQuery = queryBuilder.parseQuestion(request.getQuestion());
        try {
            results = queryManager.executeQuery(sparqlQuery);
        } catch (FileNotFoundException e) {
            Log.error(e, "FileNotFoundException");
        } catch (IOException e) {
            Log.error(e, "IOException");
        }
        return results;
    }

}

英语

Angular 服务类:

@Injectable()
export class QueryService {
    //URL  parts for http request
    host = 'http://localhost:8090/api/query/';

    httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
            'Access-Control-Allow-Headers': 'Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token'
        })
    };


    constructor(private _http: HttpClient) {
    }

    getAllData(): Observable<any> {
            let body = { 'question': 'init' };
            return this._http.post(this.host, body, this.httpOptions).pipe(
                map(
                    (response) => {
                        return response['results']['bindings'];
                    }
                )
            );
           ....
}

状态和问题

Spring boot REST API作为jar启动,并在端口8090处提供。 我可以使用一个安静的客户端(例如邮递员)成功发出POST请求。

nohup java -jar /rest.jar &

http-server通过以下命令在端口4200上为Angular应用提供服务:

http-server /path/to/dist -p 4200

Angular应用程序显示在http://<ip>/中,这意味着NGINX会选择位置并将流量重定向到端口4200。

问题可能与CORS有关,因为从前端到后端发出请求时出现以下错误。

  

OPTIONS http://localhost:8090/api/query/ net :: ERR_CONNECTION_REFUSED

我知道OPTIONS是预先发出的飞行前请求。如果不成功,则实际的POST请求失败。

在图片下方显示: options error

我还遇到了另一个错误,该错误更隐秘,并且没有显示很多信息。 在图片下方显示: cryptic error

我认为NGINX或angular-app都缺少一些CORS配置。

注意: -要添加的另一件事是,角度应用在加载后会自动从http://<ip>/重定向到http://<ip>/map-page。它被实现为其默认路由。我不知道这是否可能是个问题。

0 个答案:

没有答案