簡體   English   中英

Angular 設置與 nginx 無法命中 api

[英]Angular setup with nginx cannot hit the api

我是 Angular 開發的新手。 所以我有一個嚴重的問題是我無法在服務器上部署 angular

如果我在本地嘗試,代碼運行良好並且可以使用代理訪問 api

對於 Api 使用 spring 構建並部署在heroku

對於 Angular,我使用 Aws Lightsail 和 nginx 配置

  1. 我正在運行ng build以獲取 dist 文件夾
  2. 然后我將dist/my-folder-generate/中的所有文件移動到/var/ww/html
  3. 當我通過瀏覽器打開時,Angular 運行良好,但我無法點擊 api

這是我的 nginx 配置

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    
    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;
    
    server_name _;
    
    location / {
       try_files $uri $uri/ /index.html;
       error_page 405 =200 $uri;
    }
}

這是我的angular.json

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "my-app:build:production",
              "proxyConfig": "src/proxy.conf.json"
            },
            "development": {
              "browserTarget": "my-app:build:development",
              "proxyConfig": "src/proxy.conf.json"
            }
          },
          "defaultConfiguration": "development",
          "options": {
            "browserTarget": "my-app:build",
            "proxyConfig": "src/proxy.conf.json"
          }
 },

對於proxy.conf.json

{
  "/api": {
      "target": "https://my-api.herokuapp.com",
      "secure": false,
      "logLevel": "debug",
      "changeOrigin": true
  }
}

這就是我使用 api 的方式

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
const AUTH_API = '/api/';
const httpOptions = {
  headers: new HttpHeaders({
    accept: ' application/json',
    'Content-Type': ' application/json',
  }),
};
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private http: HttpClient) {}
  login(username: string, password: string): Observable<any> {
    return this.http.post(
      AUTH_API + 'auth/login',
      {
        username,
        password,
      },
      httpOptions
    );
  }
}

確保此配置在本地運行良好但在服務器上運行良好,有人可以幫助我嗎? 我可能對服務器配置有誤嗎?

基於 @mojtaba 對 add /api的建議。 所以我像這樣添加 nginx 配置

location /api {
  proxy_method POST;
  proxy_http_version 1.1;
  proxy_pass https://my-api.herokuapp.com;

}

所以對於像我一樣有麻煩和同樣情況的人,你可以使用這個塊

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    
    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;
    
    server_name _;
    
    location / {
       try_files $uri $uri/ /index.html;
       error_page 405 =200 $uri;
    }
}

location /api {
  proxy_method POST;
  proxy_http_version 1.1;
  proxy_pass https://my-api.herokuapp.com;    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM