使用 Nuxtjs 访问 Django api 时出现 CORS 错误 [重复]

Posted

技术标签:

【中文标题】使用 Nuxtjs 访问 Django api 时出现 CORS 错误 [重复]【英文标题】:CORS error when accessing Django api with Nuxtjs [duplicate] 【发布时间】:2019-08-29 14:43:34 【问题描述】:

我有一个 Nuxtjs 前端和一个 Django 后端。我想使用我的后端 api 并拥有以下 index.vue :

    <template>
      <div class="container">
        <h1> data </h1>
      </div>
    </template>

    <script>
    import axios from 'axios'

    export default 
      async asyncData( params ) 
        // We can use async/await ES6 feature
        const  data  = await axios.get(`localhost:8000/api`)
        return  data 
      
    

</script>

我的 nuxt.config.js 有这个代码:

  axios: 
    baseURL: 'localhost:8000',
    proxyHeaders: false,
    credentials: false,
    mode: 'no-cors'
  ,

我的 Django settings.py 应该没问题,因为它安装了 corsheaders:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'django_celery_results',
    'django_celery_beat',
    'rest_framework',
    'core',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False

不知道发生了什么或为什么 axios 仍然会引发 CORS 错误:

VM1921:1 Access to XMLHttpRequest at 'localhost:8000/api' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
(anonymous) @ VM1921:1
dispatchXhrRequest @ commons.app.js:199
xhrAdapter @ commons.app.js:33
dispatchRequest @ commons.app.js:638
Promise.then (async)
request @ commons.app.js:445
Axios.(anonymous function) @ commons.app.js:455
wrap @ commons.app.js:898
_callee$ @ pages_index.js:51
tryCatch @ commons.app.js:5762
invoke @ commons.app.js:5988
prototype.(anonymous function) @ commons.app.js:5814
asyncGeneratorStep @ vendors.app.js:31
_next @ vendors.app.js:53
(anonymous) @ vendors.app.js:60
(anonymous) @ vendors.app.js:49
asyncData @ pages_index.js:69
promisify @ app.js:2841
(anonymous) @ app.js:1089
_callee4$ @ app.js:1059
tryCatch @ commons.app.js:5762
invoke @ commons.app.js:5988
prototype.(anonymous function) @ commons.app.js:5814
asyncGeneratorStep @ vendors.app.js:31
_next @ vendors.app.js:53
Promise.then (async)
asyncGeneratorStep @ vendors.app.js:41
_next @ vendors.app.js:53
Promise.then (async)
asyncGeneratorStep @ vendors.app.js:41
_next @ vendors.app.js:53
Promise.then (async)
asyncGeneratorStep @ vendors.app.js:41
_next @ vendors.app.js:53
Promise.then (async)
asyncGeneratorStep @ vendors.app.js:41
_next @ vendors.app.js:53
(anonymous) @ vendors.app.js:60
(anonymous) @ vendors.app.js:49
_render @ app.js:1170
render @ app.js:787
_callee5$ @ app.js:1478
tryCatch @ commons.app.js:5762
invoke @ commons.app.js:5988
prototype.(anonymous function) @ commons.app.js:5814
asyncGeneratorStep @ vendors.app.js:31
_next @ vendors.app.js:53
Promise.then (async)
asyncGeneratorStep @ vendors.app.js:41
_next @ vendors.app.js:53
(anonymous) @ vendors.app.js:60
(anonymous) @ vendors.app.js:49
_mountApp @ app.js:1504
mountApp @ app.js:1402
Promise.then (async)
(anonymous) @ app.js:550
./.nuxt/client.js @ app.js:1506
__webpack_require__ @ runtime.js:787
fn @ runtime.js:150
0 @ app.js:3779
__webpack_require__ @ runtime.js:787
checkDeferredModules @ runtime.js:46
webpackJsonpCallback @ runtime.js:33
(anonymous) @ app.js:1
app.js:540 Error: Network Error
    at createError (commons.app.js:565)
    at XMLHttpRequest.handleError (commons.app.js:108)
    at XMLHttpRequest.send (<anonymous>:1:781)
    at dispatchXhrRequest (commons.app.js:199)
    at new Promise (<anonymous>)
    at xhrAdapter (commons.app.js:33)
    at dispatchRequest (commons.app.js:638)

【问题讨论】:

【参考方案1】:

我认为您需要将端口列入白名单

在settings.py中

CORS_ORIGIN_WHITELIST = (
    'http://190.0.0.21:8080',   # server ip
    'localhost:8000',           # local host
    '*'                         # allow all
)

【讨论】:

将我的端口列入白名单很可能是个好主意,但我已经有 CORS_ORIGIN_ALLOW_ALL = True【参考方案2】:

您在网址中错过了协议。

    const  data  = await axios.get(`http://localhost:8000/api`)

【讨论】:

以上是关于使用 Nuxtjs 访问 Django api 时出现 CORS 错误 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

NuxtJs 如何使用 axios filter api?

无法访问 api post 方法,总是请求 OPTIONS

dist 之后的 nuxtjs/proxy url axios

使用本地策略实现 nuxtjs/auth 的问题

在 Vue 2 / Nuxt / Typescript / @nuxtjs-composition-api 项目中使用 VSCode Volar 扩展

从 nuxtjs 中的外部 js 文件访问存储