Django Rest Framework 的設(shè)置
pip install django-cors-headers
在Django項(xiàng)目配置文件settings.py中,添加應(yīng)用:
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'
)
更詳細(xì)的配置信息,看這兒。
ExpressJS
在ExpressJS應(yīng)用中,添加如下路徑信息:
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
});
參考這兒。