【已解决】已拦截跨域请求:同源策略禁止读取位于接口的远程资源:原因:CORS缺少Access-Contorl-Allow-Origin

前后端开发跨域问题

  • 1 问题记录
  • 2 前端
    • 2.1新手配置:有问题
      • 2.1.1纠错处:
      • 2.1.2注意
    • 2.2老手配置:正常
  • 3 后端
    • 3.1新手配置:有问题
      • 3.1.1纠错处:
      • 3.1.2注意
    • 3.2老手配置:正常
  • 4 总结

有用请留下你的足迹,让更多人的人看到,谢谢

1 问题记录

今天笔者有一次遇到前后端跨域问题,下面小编详细的记录下整个过程:
环境是:后端在公司,前端在远程,两人协同开发
后端写好接口,并发布在外网后,接下来就是远程前端的对接接口阶段,前端在配置接口时,配置成功,在测试访问时,浏览器报“已拦截跨域请求:同源策略禁止读取位于接口的远程资源:原因:CORS缺少Access-Contorl-Allow-Origin”问题,错误提示是“cors跨域问题”,后端看到只接受到了预请求,此刻,两者都不确定是谁的问题,都着手解决这个问题,好了,小编暂时代替他配合后端联调,首先用之前已经正常的登录界面来配合他来联调,联调时,还是出现相同的问题,此时判断出是后端请求规则配置有问题。解决方法本篇文章后面会记录。待后端解决后,我两联调正常后,接下来就是远程前端和后端的联调,结果调试还是出现问题,说明此刻问题是前端的配置有问题,果不其然,小编将自己的main.js文件配置给他后,解决啦,问题到此结束,下面将详细记录解决方案!!

2 前端

2.1新手配置:有问题

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import router from './router'
import store from './store'

Vue.config.productionTip = false
Vue.prototype.$axios = axios
Vue.prototype.$http = axios // 全局挂载axios
const base_url = 'httt://117.xx.xx.198:1024/'
axios.defaults.baseURL = base_url

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8' /
new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')
错误

2.1.1纠错处:

  • axios其全局定义两次,去掉或注释一个
  • main.js文件中axios的引入应在store引入之后,位置不对

2.1.2注意

了解引入的规则,一般的自己写的js或者json文件引入时,写到原有引入文件的后面。
写代码的,没有一个不知道代码是自上而下运行的,因此自写的文件引入在原引入文件之前,那就是你的文件先运行,你的文件运行的内部代码逻辑就会跑偏。

2.2老手配置:正常

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// import elementui from 'element-ui'
// import "element-ui/lib/theme-chalk/index.css"  //element ui样式
import axios from 'axios'

Vue.config.productionTip = false
// Vue.use(elementui)

Vue.prototype.$http = axios

// const base_url = ''
const base_url = 'http://117.xx.xx.198:1024'
axios.defaults.baseURL = base_url
localStorage.setItem('base_url', base_url)

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'


new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

3 后端

后端是python写的,配置于setting.py文件中

3.1新手配置:有问题

"""
Django settings for Project project.

Generated by 'django-admin startproject' using Django 3.1.13.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'evwet_y=%^7$b)r3o9we47^5h&@_)ekojx5v+tlh!$tgo)$5ux'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
     '_____________',   #缺少cors的headers配置导入
    'django.contrib.staticfiles',
    'user',
    'rest_framework',
    'devices'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    '______________________________________',     #缺少一个cors的中间件
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'StudentCourseSelection.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

3.1.1纠错处:

  • INSTALLED_APPS 处配置不全,加上 corsheaders
  • MIDDLEWARE 中应配置 corsheaders.middleware.CorsMiddleware

3.1.2注意

问题定位,是否遗漏

3.2老手配置:正常

"""
Django settings for Project project.

Generated by 'django-admin startproject' using Django 3.1.13.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'evwet_y=%^7$b)r3o9we47^5h&@_)ekojx5v+tlh!$tgo)$5ux'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'corsheaders',  #####################
    'django.contrib.staticfiles',
    'user',
    'rest_framework',
    'devices'
]

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

ROOT_URLCONF = 'Project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'StudentCourseSelection.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

4 总结

小编觉得工作上,出现问题,要及时配合处理,做到更好、更快的解决问题,告诫大家的同时也是告诫我自己,要认真仔细,对待代码也是如此,相信大家也经常会因为一个字母而引发的问题吧,你只需要认真即可。

你可能感兴趣的:(vue.js,javascript,CORS跨域)