【问题标题】:”No Access-Control-Allow-Origin” for response from nginx API endpoint来自 nginx API 端点的响应的“No Access-Control-Allow-Origin”
【发布时间】:2018-02-04 11:58:18
【问题描述】:

我遇到的错误似乎是 CORS 问题。

我正在尝试通过HttpClient 向我的 RESTful API 发出 POST 请求,如下所示:

import {Component, OnInit} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {HttpClient, HttpParams, HttpHeaders} from "@angular/common/http";

import { Test }             from './test';
import { TestResponse }     from './test.response';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';

import * as _ from 'lodash';

@Component({
    selector: 'my-tests',
    templateUrl: './tests.component.html',
    styleUrls: ['./tests.component.css']
})

export class TestsComponent implements OnInit {

    // URL to web api
    private url = 'http://172.19.0.5/api/tests';

    tests$: Observable<Test[]>;

    private httpheadersPost = new HttpHeaders().set("Content-Type", "application/json");

    constructor(private http:HttpClient) {
    }

    ngOnInit() {
        // console.log(this.httpheadersPost);
        this.tests$ = this.http
            .get<TestResponse[]>(this.url)
            .do(console.log)
            .map(data => _.values(data["hydra:member"]));
    }

    // Implementation of the add() function
    add(name: string): void {
        // console.log('header:'+this.httpheadersPost);
        // console.log(this.httpheadersPost);
      name = name.trim();
      if (!name) { return; }
      this.http.post(this.url, {"name":name}, {"headers":this.httpheadersPost} )
        .subscribe(
            val => {
                console.log("POST call successful value returned in body", val);
            },
            response => {
                console.log("POST call in error", response);
            },
            () => {
                console.log("The POST observable is now completed.");
            }
        );
    }


}

这是我的 RESTful API 的 nginx 服务器的配置:

server {

    server_name symfony.dev;
    root /var/www/symfony/public;

    location / {
        add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
        #add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
        add_header 'Access-Control-Allow-Origin' '*';
        try_files $uri /index.php$is_args$args;

    }

    location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|eof|woff|ttf)$ {
        add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
        #add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
        add_header 'Access-Control-Allow-Origin' '*';

        if (-f $request_filename) {
            expires 30d;
            access_log off;
        }
    }

    location ~ \.php$ {
        add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
        #add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
        add_header 'Access-Control-Allow-Origin' '*';
        fastcgi_pass php:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    error_log /var/log/nginx/symfony_error.log;
    access_log /var/log/nginx/symfony_access.log;
}

RESTful API 和 Angular 应用程序是通过 docker-compose 创建的,因此容器的 IP 地址不同。

我得到的错误是:

**选项http://172.19.0.5/api/tests **

XMLHttpRequest 无法加载 http://172.19.0.5/api/tests。对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4203” 使用权。响应的 HTTP 状态代码为 405。

IMO 中的错误很奇怪。事实上,我已经提供了 headers + RESTful API 的 nginx 服务器,其中 Access-Control-Allow-Origin 已经设置好了。

感谢您的帮助。

【问题讨论】:

  • web 服务是使用javaasp.net 开发的还是?
  • 响应发送到的服务器必须实现支持 OPTIONS 方法,但是响应中的 405 状态码表明服务器当前表示它不允许 OPTIONS 请求。有关详细信息,请参阅stackoverflow.com/questions/43871637/…的答案
  • 您确定您的服务器没有响应错误吗?
  • RESTful API 由 Symfony3.4 创建,api-platform

标签: nginx cors


【解决方案1】:

问题是 CORS 不能以这种方式工作。当浏览器想要在 API 上测试 CORS 时,它会向它发送一个 OPTIONS 请求。此请求应使用 CORS 标头和 http 代码 204 进行响应。

所以你需要像下面这样更新你的 nginx 配置。这不准确,但应该能让你继续前进

server {

    server_name symfony.dev;
    root /var/www/symfony/public;

    location / {

        # Match host using a hostname if you like
        #if ($http_origin ~* (https?://.*\.tarunlalwani\.com(:[0-9]+)?$)) {
        #   set $cors "1";
        #}
        set $cors "1";

        # OPTIONS indicates a CORS pre-flight request
        if ($request_method = 'OPTIONS') {
           set $cors "${cors}o";
        }

        # OPTIONS (pre-flight) request from allowed
        # CORS domain. return response directly
        if ($cors = "1o") {
           add_header 'Access-Control-Allow-Origin' '$http_origin' always;
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
           add_header 'Access-Control-Allow-Credentials' 'true' always;
           add_header 'Access-Control-Allow-Headers' 'Origin,Content-Type,Accept' always;
           add_header Content-Length 0;
           add_header Content-Type text/plain;
           return 204;
        }

        add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
        #add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
        add_header 'Access-Control-Allow-Origin' '*';
        try_files $uri /index.php$is_args$args;

    }

    location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|eof|woff|ttf)$ {
        add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
        #add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
        add_header 'Access-Control-Allow-Origin' '*';

        if (-f $request_filename) {
            expires 30d;
            access_log off;
        }
    }

    location ~ \.php$ {
        add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
        #add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
        add_header 'Access-Control-Allow-Origin' '*';
        fastcgi_pass php:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    error_log /var/log/nginx/symfony_error.log;
    access_log /var/log/nginx/symfony_access.log;
}

我最近使用了一个类似的配置来为 grafana (No response from Grafana via AJAX) 启用 CORS。所以这也应该对你有用

【讨论】:

    猜你喜欢
    • 2017-12-29
    • 2018-02-14
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2021-08-12
    • 2019-09-09
    相关资源
    最近更新 更多