前端运行在 localhost:3000
服务器运行在 localhost:9000
我可以在不访问 cookie 的情况下发出 CORS 请求。
示例 Axios 请求
axios.post(SERVER+'/createUser', params)
.then( resp=>{
//not important
});
(working: 能够访问其他服务器的资源)
我无法保存/发送服务器 localhost:9000
设置的 HttpOnly cookie [ session 实现]
预期流程
调用 localhost:9000/authenticate
localhost:9000/authenticate
返回带有 HttpOnly cookie 的响应
对 localhost:9000
的后续请求携带此 cookie
为了尝试使用 axios 访问此 cookie,我添加了 header withCredentials:true
由 documentation for axios 引用.为清楚起见:
let headers = {
withCredentials:true
}
export function authenticate(creds){
return dispatch => {
axios.post(SERVER+'/authenticate', creds, headers)
.then( resp => {
//not important
});
};
}
之后我收到以下错误:
Failed to load http://localhost:9000/authenticate: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
为清楚起见,第一个 (OPTIONS) 请求已发送,在“成功”响应后,将抛出错误。选项要求:
我的服务器使用 Flask-Cors
库,在读取 cookie documentation 之后和其他一些链接,这就是为 CORS 设置服务器的方式
... normal app init
app = Flask(__name__, static_url_path='/static')
...
cors = CORS(app, origins=["http://localhost:3000"], headers=['Content-Type'], expose_headers=['Access-Control-Allow-Origin'], supports_credentials=True)
...
@app.route('/authenticate', methods=['POST'])
def authenticate():
...
我只将方法设置为 POST 因为 (1) cookie documentation也将其限制为 POST 和 (2) OPTIONS 请求似乎通过了(如图所示)和 (3) 当我确实将 OPTIONS 作为路由的可能方法时,当第一个请求被发送时,它进入方法而且我不知道要返回什么,所以如果有人知道包含 OPTIONS 方法时正确的响应是什么,请发帖。
其他链接
https://github.com/axios/axios/issues/569
CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
最佳答案
代码看起来像是将 withCredentials
定义为 HTTP header 。但这并不完全是它的工作原理。
withCredentials
实际上是一个启用 http header 的选项,但它本身并不是 http header 。
尝试像这样创建 promise :
const axiosWithCookies = axios.create({
withCredentials: true
});
const promise = axiosWithCookies.get(url);
生成的 http header 实际上如下所示。 但是您不必手动添加它。如果您像上面那样创建 axios 实例,这将得到处理。
Cookie: JSESSIONID=...
关于javascript - 配置 Axios 和 Flask 以使用 CORS 和 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51064452/