CORS 缺少允许来源

时间:2021-01-24 14:23:48

标签: vue.js cors nuxt.js django-cors-headers

我的服务器(用 Django 编写)正在 http://localhost:8000 运行。

Nuxt 应用程序正在 http://localhost:3000 运行。

当我向服务器发送请求(如 http://localhost:8000/api/v1/user/position/)时,我在 firefox 浏览器中收到以下错误。

<块引用>

跨域请求被阻止:同源策略不允许读取 位于 http://localhost:8000/api/v1/user/position/ 的远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

火狐:

error in firefox network tab

Chrome:

Error in chrome network tab

我看到了 this linkthis,但我不知道问题出在哪里?

以下是我的 nuxt.config.js 文件的一部分。

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
],
axios: {
    baseURL: 'http://localhost:8000/api/v1/', 
},

以及我发送请求的功能:

async getAllPosition() {
    this.loading_position = true;
    await this.$axios.get('user/position/').then(response => {
          this.position = response.data;
    }).finally(() => {
         this.loading_position = false;
        })
 }

我认为是关于代理的,但我不知道如何配置它。

4 个答案:

答案 0 :(得分:3)

正如 @BananaLama@TMFLGR 在他们的回答中提到的:

我需要在我的 Access-Control-Allow-Origin 服务器中指定 Django 标头以允许跨源请求。为此,我使用了 django-cors-headers package 并在 seetings.py 部分允许它,结果得到了很好的返回。

// settings.py

INSTALLED_APPS = [
    ...
    'corsheaders',
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

CORS_ALLOWED_ORIGINS  = [
    "http://localhost:3000",
]

结果:

enter image description here

答案 1 :(得分:1)

如错误消息所示:您需要在服务器中指定一个 Access-Control-Allow-Origin-header 以允许跨源请求。 (是的 ::3000 和 ::8000 是不同的起源)。当请求另一个源时,现代浏览器将触发选项(飞行前)请求以检查 Access-* 标头。您必须至少使用 Access-Control 标头来回答这些 OPTIONS 请求。 Access-Control-Allow-Origin: localhost:3000 应该适合开发。

有关 CORS 和浏览器选项的更多信息,请访问:
https://enable-cors.org/
Why is an OPTIONS request sent and can I disable it?

答案 2 :(得分:1)

可以设置转发代理来处理跨域

nuxt.config.js:


export default {
  ...
  proxy: {
    '/api': { 
      target: 'http://localhost:8000',
      pathRewrite: {
        '^/api': '/api',
        changeOrigin: true
      }    
    }
  },
}

答案 3 :(得分:1)

正如@TMFLGR 提到的: 向您的服务器添加一个 OPTION-Request 处理程序并指定一个 Access-Control-Allow-Origin Header。代理适用于开发,但在生产中您不应该这样做。