nginx 为什么在远程服务器上测试应用程序时发出http请求时会出现405错误?

krugob8w  于 2022-11-21  发布在  Nginx
关注(0)|答案(1)|浏览(208)

我试图找出在临时上下文中发出http请求时出现405错误的原因。
我展示了相关组件
proxy.conf.json

{
  "/connect/*": {
    "target": "http://portal.test.com/backend",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

login.service.ts

@Injectable({
  providedIn: 'root',
})
export class LoginService {
  private readonly ENDPOINT = '/connect/token';

  constructor(private readonly httpClient: HttpClient) {}

  login(credentials: CredentialsModel): Observable<SuccessfulLoginModel> {
    const { username, password } = credentials;
    const body = new URLSearchParams();
    body.set('grant_type', 'password');
    body.set('username', username);
    body.set('password', password);
    body.set('scope', 'offline_access openid profile');
    const options = this.getHTTPOptions();

    return this.httpClient.post<any>(this.ENDPOINT, body.toString(), options);
  }

  refreshToken(token: string): Observable<SuccessfulLoginModel> {
    // ...
  }

  private getHTTPOptions() {
    return {
      headers: new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded')
        .set(
          'Authorization',
          'Basic ' +
            btoa(`${environment.client_id}:${environment.client_secret}`)
        ),
    };
  }
}

在本地调用/connect/token端点时,我得到以下响应

HTTP/1.1 200 OK
x-powered-by: OrchardCore
Access-Control-Allow-Origin: *
server: nginx/1.23.1
date: Sun, 13 Nov 2022 01:46:27 GMT
content-type: application/json;charset=UTF-8
content-length: 12337
cache-control: no-store
expires: Thu, 01 Jan 1970 00:00:00 GMT
pragma: no-cache
set-cookie: .AspNetCore.Mvc.CookieTempDataProvider=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/backend; samesite=lax; httponly
x-content-type-options: nosniff
referrer-policy: no-referrer
connection: close

在staging中,当调用/connect/token端点时,我得到以下响应

HTTP/1.1 405 Not Allowed
server: nginx/1.23.1
date: Sun, 13 Nov 2022 01:48:19 GMT
content-type: text/html
content-length: 157

你能帮我指出这种行为的原因吗?提前感谢

更新1

我已经在远程服务器上重现了这个行为,

docker run --name habanos -v /home/mario/projects/spa/dist/app-name:/usr/share/nginx/html/:ro -d -p 8080:80 nginx:latest

根据Angular 文档,我设置了推荐的前端控制器模式Web应用程序

try_files $uri $uri/ /index.html;

上面的代码使应用程序可以访问。
设置error_page 405 =200 $uri;将405更改为200 r,但仍获取html内容
如何正确配置nginx来处理POST请求?

5f0d552i

5f0d552i1#

该问题的解决方案是在代理配置中使用基本url
原始目标URL如下:

{
  "/connect/*": {
    "target": "http://portal.test.com/backend",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

使用基本URL作为目标URL修复了该问题

{
  "/backend/*": {
    "target": "http://portal.test.com",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

通过这种方式,从服务调用的端点看起来类似于以下内容:

private readonly ENDPOINT = '/backend/connect/token';

相关问题