为什么在设置访问控制允许源时收到 CORS 错误?



>问题

响应标头的Access-Control-Allow-Origin与请求Origin标头匹配,但我仍然收到错误Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://myappname.herokuapp.com/api/v1/products. (Reason: CORS request did not succeed).[Learn More]

响应标头

HTTP/1.1 308 PERMANENT REDIRECT
Connection: keep-alive
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: authorization, content-type
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Access-Control-Allow-Origin: http://localhost
Content-Length: 311
Content-Type: text/html; charset=utf-8
Date: Thu, 04 Apr 2019 10:03:39 GMT
Location: http://mpappname.herokuapp.com/api/v1/products/
Server: waitress
Via: 1.1 vegur

请求标头

Host: mpappname.herokuapp.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization,content-type
Referer: http://localhost/admin/main/products/create
Origin: http://localhost
DNT: 1
Connection: keep-alive

背景

生成标头的代码如下,但我更关心的是理解为什么 CORS 预检拒绝这一点。这适用于具有产品 CRUD 设计和基于令牌的身份验证的烧瓶 API。

切割版

from flask_cors import CORS
def create_app(config_name):
...
CORS(app, origins="http://localhost",
allow_headers=["Content-Type", "Authorization", "Access-Control-Allow-Credentials"],
supports_credentials=True)
...
return app

完整版

from flask import Flask
from config import config
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
db.init_app(app)
CORS(app, origins="http://localhost",
allow_headers=["Content-Type", "Authorization", "Access-Control-Allow-Credentials"],
supports_credentials=True)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .api import api as api_blueprint
app.register_blueprint(api_blueprint, url_prefix='/api/v1')
return app

我正在请求

http://mpappname.herokuapp.com/api/v1/products

而不是

http://mpappname.herokuapp.com/api/v1/products/

也许对某些人来说很明显,但我需要明确阅读这篇博文才能理解这一点:

https://airbrake.io/blog/http-errors/308-permanent-redirect

308永久重定向的出现通常不需要太多用户干预。所有现代浏览器将自动检测 308 永久重定向响应代码,并自动处理重定向到新 URI 的操作。发送 308 代码的服务器还将包含一个特殊的 Location 标头,作为它发送到客户端的响应的一部分。此位置标头指示可在其中找到所请求资源的新 URI。例如,如果客户端发送 HTTP POST 方法请求作为登录 https://airbrake.io URL 的尝试,则可以将 Web 服务器配置为将此 POST 请求重定向到其他 URI,例如 https://airbrake.io/login。在这种情况下,服务器可能会响应 308 永久重定向代码,并在响应中包含位置: https://airbrake.io/login 标头。这会通知用户代理(浏览器)服务器已收到 POST 请求数据(登录信息),但资源已永久移动到 https://airbrake.io/login 的位置标头 URI

相关内容

  • 没有找到相关文章

最新更新