如何在DjangoRestFramework和ExpressJS中分别设置CORS

Django Rest Framework 的设置

安装包django-cors-headers:

pip install django-cors-headers

在Django项目配置文件settings.py中,添加应用:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

中间件部分还需添加:

MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

添加CORS白名单,示例:

CORS_ORIGIN_WHITELIST = (
    'google.com',
    'hostname.example.com',
    'localhost:8000',
    '127.0.0.1:9000'
)

更详细的配置信息,看这儿。

ExpressJS

在ExpressJS应用中,添加如下路径信息:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

参考这儿。

你可能感兴趣的:(如何在DjangoRestFramework和ExpressJS中分别设置CORS)