我目前使用Flask进行Python后端。出于原型的身份验证目的,我们使用Flask-Basic-Auth。我们很难通过Chrome发送请求,但我们在IE上取得了成功。我们了解Chrome和Firefox在处理OPTIONS预检响应方面存在一个错误。问题是我们如何暂时解决这个问题?我们已尝试在后端代码中响应OPTIONS请求,但取得了如此成功。我们现在已经没有想法了。我将在下面粘贴一些您可能会觉得有用的信息:
错误消息
Response for preflight has invalid HTTP status code 401
响应标题:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, api_key, authorization
Access-Control-Allow-Methods:GET, PUT, POST, DELETE
Access-Control-Allow-Origin:http://localhost:3000
Content-Length:0
Content-Type:text/html; charset=utf-8
Date:Mon, 22 May 2017 12:47:59 GMT
Server:Werkzeug/0.12.2 Python/2.7.13
WWW-Authenticate:Basic realm=""
请求标题:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en,en-US;q=0.8,de;q=0.6
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:127.0.0.1:20177
Origin:http://localhost:3000
Referer:http://localhost:3000/login.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
我们用于发起请求的Javascript代码:
$('.login').on('click', function() {
var username = $('.username').val();
var password = $('.password').val();
$.ajax({
url: serverURL, // We have a constant for this elsewhere
type: 'GET',
xhrFields: {
withCredentials: true
},
headers: {
Authorization: `Basic ${username}:${password}`
}
}).done(function() {
console.log('Success')
}).fail(function(error) {
console.log(error)
console.log('Error')
})
});
在Python方面,我们覆盖了Flask-Basic-Auth库提供的check_credentials方法。我不相信这会对这个问题的调试有所帮助,但我会把它放在这里以防万一:
def check_credentials(self, username, password):
print('Checking..')
print(username)
print(password)
conn = lite.connect('D:\s\data\sd-sqlite.db')
cur = conn.cursor()
cur.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))
data = cur.fetchall()
if len(data) == 0:
print('No users found')
return False
elif len(data) > 0:
print('User Found!')
return True
BasicAuth.check_credentials = check_credentials
以下代码也是在每个请求中添加已接受标头的代码:
@APP.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type, api_key, authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE')
response.headers.add('Access-Control-Allow-Credentials', 'true')
return response
如果你们可以发现任何可能错误的信息,或者用Python处理OPTIONS请求的最佳方法就是很棒。就像我说的那样,我们之前曾试图处理它们,但没有运气。我们知道有一种解决方法,我们找不到它!
提前感谢您的任何帮助