响应标头的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设计和基于令牌的身份验证的Flask 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
答案 0 :(得分:0)
我正在请求
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标头,作为发送给客户端的响应的一部分。此Location标头指示可以在其中找到所请求资源的新URI。例如,如果客户端发送HTTP POST方法请求以尝试登录https://airbrake.io URL,则可以将Web服务器配置为将该POST请求重定向到其他URI,例如{{3} }。在这种情况下,服务器可以使用308永久重定向代码进行响应,并在响应中包含Location:https://airbrake.io/login标头。这通知用户代理(浏览器)服务器已接收到POST请求数据(登录信息),但是资源已被永久移动到https://airbrake.io/login的Location头URI中。