我正在使用Python和Flask,并创建了一个REST API,我需要我的Vue应用程序与它交互并获取数据,但我没有'Access-Control-Allow-Origin'头。
我从nginx添加了那个头(所以我可以代理API,因为开发服务器没有任何允许跨域访问的选项)我试过使用jQuery而不是vue-resource,结果成功了。
nginx配置:
server {
listen 5089;
access_log off;
error_log /dev/null crit;
location / {
add_header 'Access-Control-Allow-Headers' 'content-type';
add_header 'Access-Control-Allow-Origin' '*';
proxy_pass http://localhost:5000;
proxy_read_timeout 90;
}
}
Vue组件:
<template>
<div id="app">
<div id="nav">
<router-link to="/" class="btn-dark">Home</router-link>
|
<router-link to="/about">About</router-link>
</div>
<label>User ID:
<input type="text" v-model="auth.id" required/>
</label>
<label>
Password:
<input type="text" v-model="auth.password"/>
</label>
<button v-on:click.prevent="getToken">Submit</button>
</div>
</template>
<script>
export default {
data () {
return {
auth: {
id: '',
password: ''
}
}
},
methods: {
getToken: function (token) {
this.$http.post('http://localhost:5089/auth', {
UID: this.auth.id,
pass: this.auth.password
}).then(function (data) {
console.log(data)
})
}
}
}
</script>
API路由代码:
@app.route('/auth', methods=['POST'])
def authenticate():
print(request.form)
for data in request.form:
try:
jsonParsed = json.loads(data)
id = jsonParsed['UID']
allegedPass = jsonParsed['pass']
except Exception:
return jsonify({
'message': 'Oopsie Whoopsie what a nice cat, look'
})
if id and allegedPass:
authFile = open('auth.json', 'r')
authData = json.load(authFile)
authFile.close()
try:
hashedPass = authData[str(id)]['pass']
except Exception:
return jsonify({
'message': 'Oopsie Whoopsie look, a foxie'
})
if hashedPass == allegedPass:
token = jwt.encode({'id': id, 'pass': allegedPass, 'exp': datetime.utcnow() + timedelta(minutes=15)},
app.config['secret'])
return jsonify({
'token': token.decode('UTF-8')
})
else:
return jsonify({
'message': 'GTFO'
})
else:
return jsonify({
'message': 'Kill yourself already.'
})
它应该向应用程序发送一个令牌,但我在控制台中收到以下错误:
POST http://localhost:5089/auth 500 (INTERNAL SERVER ERROR)
Access to XMLHttpRequest at 'http://localhost:5089/auth' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
在API终端上,我得到:
127.0.0.1 - - [06/Apr/2019 09:24:13] "OPTIONS /auth HTTP/1.0" 200 -
ImmutableMultiDict([])
127.0.0.1 - - [06/Apr/2019 09:24:13] "POST /auth HTTP/1.0" 500 -
Traceback (most recent call last):
.
.
.
File "/home/sids/Projects/laboratory/py/server.py", line 58, in authenticate
if id and allegedPass:
UnboundLocalError: local variable 'id' referenced before assignment
2条答案
按热度按时间bjp0bcyl1#
结果是vue-resource模块没有正确发送数据或者没有正确接收数据;因此,当我试图解析请求表单时,出现了一个错误,导致了这个问题,浏览器认为Origin被阻止了,尽管它知道;但是,我现在使用jQuery;这行得通
r1zk6ea12#
我也遇到了同样的问题,这就是我的表现:
1)安装Flask-CORS扩展:
2)导入扩展并在Flask应用中使用: