vue.js 和 django 中的 Access-Control-Allow-Origin 问题

Wei*_*ung 1 django nginx cors django-rest-framework vue.js

我在自己的电脑上部署了我的服务,一切都运行良好,我决定把它放在我的服务器上。但我发现有些请求受到“CORS”的限制,而有些则不受限制。

Web 服务器是部署在 Linux 上的 Nginx。后端框架为Django,DRF提供api服务,前端框架为Vue.js,Ajax请求库使用axios。代码在我自己的 Mac 上运行非常完美,没有 CORS 问题。但它在服务器上出现了问题。顺便说一句,Vue.js 中路由的模式是history模式。

这是我的 Nginx 配置代码:

server {
        listen  80;
        server_name 167.179.111.96;
        charset utf-8;

        location / {
                root /root/blog-frontend/dist;
                try_files $uri $uri/ @router;
                index index.html;
                add_header Access-Control-Allow-Origin *;
                add_header Access-Control-Allow-Methods *;
        }

        location @router {
            rewrite ^.*$ /index.html last;
        }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 Vue.js 代码,它有“CORS”问题。

主文件

Vue.prototype.API = api
Vue.prototype.GLOBAL = global
Vue.prototype.$axios = Axios;

Axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
Axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'
Run Code Online (Sandbox Code Playgroud)

重定向.vue

<template>
  <div id="notfound">
    <div class="notfound">
      <div class="notfound-404">
        <h1>Redirect</h1>
      </div>
      <h2>Wait a few seconds, page is redirecting</h2>
      <p>You are logging...authorization code is {{code}}</p>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'redirect',
    data(){
      return{
        code:''
      }
    },
    created () {
      this.code = this.$route.query.code
      this.$axios({
        method: 'get',
        url: this.API.oauth_redirect,
        params:{
          code:this.code
        },
      }).then((response)=>{
        if (response.data.status===200){
          this.$message.success('login success')
          let data = response.data.data
          this.$store.commit('SET_TOKEN', data['token'])
          this.$store.commit('SET_USER', data)
        }
        else{
          console.log(response.data.msg)
          this.$message.error(response.data.msg)
        }
        this.$router.go(-1)
      })
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

我的后端代码:middleware.py

from django.utils.deprecation import MiddlewareMixin

CORS = {
    'Access-Control-Allow-Headers': '*',
    'Access-Control-Allow-Methods': '*',
    'Access-Control-Allow-Origin': '*'
}


class MyMiddle(MiddlewareMixin):
    def process_response(self, request, response):
        if request.method == 'OPTIONS':
            response['Access-Control-Allow-Methods'] = CORS['Access-Control-Allow-Methods']
        response['Access-Control-Allow-Headers'] = CORS['Access-Control-Allow-Headers']
        response['Access-Control-Allow-Origin'] = CORS['Access-Control-Allow-Origin']
        return response
Run Code Online (Sandbox Code Playgroud)

设置.py

import os

# production environment
if os.environ['LOGNAME'] == 'weiziyang':
    CLIENT = 'https://localhost:8080'
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'OPTIONS': {
                'database': 'mysite',
                'user': 'root',
                'password': '********',
                'charset': 'utf8mb4',
            },
        }
    }
    GITHUB_CLIENT_ID = '7198b5e59a7094f2a198'
    GITHUB_CLIENT_SECRET = '***********'
else:
    CLIENT = 'https://167.179.111.96:80'
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'OPTIONS': {
                'database': 'mysite',
                'user': 'root',
                'password': '******',
                'charset': 'utf8mb4',
                'init_command': 'SET storage_engine=INNODB;'
            },
        }
    }
    GITHUB_CLIENT_ID = '83539caeb4c865d8f3e6'
    GITHUB_CLIENT_SECRET = '***********'


# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

AUTH_USER_MODEL = 'user.BlogUsers'

CORS_ORIGIN_ALLOW_ALL = False

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1:8080',
    'http://localhost:8080',
    'http://167.179.111.96:80',
    'http://167.179.111.96'
)

ALLOWED_HOSTS = ['*']

CORS_ALLOW_METHODS = (
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS'
)

CORS_ALLOW_HEADERS = (
    'x-requested-with',
    'content-type',
    'accept',
    'origin',
    'authorization',
    'x-csrftoken'
)

Run Code Online (Sandbox Code Playgroud)

预期结果不应该包含任何 CORS 问题,因为我已经在我自己的 PC 上测试了它们。但我得到的错误信息是:

Access to XMLHttpRequest at 'http://167.179.111.96:8000/user/info/?token=714ae00539a1e66642ea815722908477e4b4e07a' from origin 'http://167.179.111.96' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

Ric*_*rdo 5

DRF 建议使用这个库django-cors-headers。来源:https : //www.django-rest-framework.org/topics/ajax-csrf-cors/#cors

使用:

pip install django-cors-headers
Run Code Online (Sandbox Code Playgroud)

然后将其添加到您已安装的应用程序中:

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]
Run Code Online (Sandbox Code Playgroud)

在你的 settings.py

CORS_ORIGIN_ALLOW_ALL=True
Run Code Online (Sandbox Code Playgroud)

这将允许所有域。您可以在 lib 文档中阅读如何进行更好的设置。像那样:

CORS_ORIGIN_WHITELIST = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000"
]
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,您还需要在 Django 中添加相应的 corsheaders 中间件: 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', (3认同)