Not able to make request to backend server in ember (error :'No Access-Control-Allow-Origin')

Not able to make request to backend server in ember (error :'No Access-Control-Allow-Origin')

我在 ember js 中设计了适配器,它向后端发送请求以获取数据但出现错误 "XMLHttpRequest cannot load https://example.com/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access." 在控制台中。

如果我在 server.The 后端使用 django 设计的 nginx 配置文件中使用以下代码,我可以解决问题。

if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }

但我不想打扰 nginx 配置。

适配器

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
    host:"https://example.com/api/",
});

如何发送请求使其不显示任何错误

不幸的是,您将不得不编辑服务器的配置文件。否则,您将不得不从与后端相同的域和端口提供应用程序。

在 settings.py:

中使用 django-cors-headers 配置它
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = (
  'x-requested-with',
  'content-type',
  'accept',
  'origin',
  'authorization',
  'x-csrftoken',
  'cache-control',
  'accept-encoding',
)