允许通过Access-Control-Allow-Origine标头进行远程API访问(Nginx / Openresty)

时间:2018-09-12 12:23:10

标签: rest api nginx axios openresty

我有我的API,该API由运行在http://v1.api.macamera.be/上的Nginx(Openresty版本)提供

当我在台式计算机上运行的前端应用(Vue2)从我的API请求GET时,网页上会显示以下“网络错误”。

控制台输出为:

Failed to load http://v1.api.macamera.be/event/:
No Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:8081' is therefore not allowed access.

Openresty是默认版本,带有内置模块'headers-more-nginx-module-0.33'

我试图解决的问题:

server {
    listen       80;
#    listen 443 ssl;

    server_name  v1.api.macamera.be;
#    server_name 127.0.0.1;

#        include snippets/ssl-params.conf;
#        ssl_certificate /etc/letsencrypt/live/v1.api.macamera.be/fullchain.pem;
#        ssl_certificate_key /etc/letsencrypt/live/v1.api.macamera.be/privkey.pem;

        root /data/sites/v1.api.macamera.be;

        access_log /data/sites/v1.api.macamera.be/logs/access.log;
        error_log /data/sites/v1.api.macamera.be/logs/error.log;

        # pour éviter les erreurs network dans les browsers (à afiner + tard!!):
#       add_header 'Access-Control-Allow-Origin' '*';
#       add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #more_set_headers    'Access-Control-Allow-Origin: *';
        more_set_input_headers "Access-Control-Allow-Origin: *";

    location /event {
      postgres_pass macamera;
      rds_json on;
      postgres_query    HEAD GET  "SELECT * FROM event";

      postgres_escape $event_id $arg_event_id;
      postgres_escape $camera_id $arg_camera_id;
      postgres_escape $date $arg_date;
      postgres_escape $file  $arg_file;
      postgres_query
        POST "INSERT INTO event (event_id, camera_id, date, file) VALUES($event_id, $camera_id, $date, $file) RETURNING *";
      postgres_rewrite  POST changes 201;
    }

    location ~ /event/(?<event_id>\d+) {
      postgres_pass macamera;
      rds_json  on;
      postgres_escape $escaped_event_id $event_id;
      postgres_query    HEAD GET  "SELECT * FROM event WHERE event_id=$escaped_event_id";
      postgres_rewrite  HEAD GET  no_rows 410;

      postgres_escape $title $arg_title;
      postgres_escape $body  $arg_body;
      postgres_query
        PUT "UPDATE articles SET title=$title, body=$body WHERE id=2 RETURNING *";
      postgres_rewrite  PUT no_changes 410;

#      postgres_query    DELETE  "DELETE FROM articles WHERE id=$escaped_id";
      postgres_query    DELETE  "DELETE FROM articles WHERE id=3";
      postgres_rewrite  DELETE  no_changes 410;
      postgres_rewrite  DELETE  changes 204;
    }

}

尽管我的“ more_set_headers'访问控制允许来源:*';”指令,仍然出现错误。

以下是GET操作中的一些调试信息:

Network Error debug:

1 个答案:

答案 0 :(得分:1)

通过移动解决

more_set_headers    'Access-Control-Allow-Origin: *';

从位置范围到服务器范围。 仍然有兴趣了解为什么openresty在所在地下不接受此指令。根据文档,应该