我将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
答案 0 :(得分:0)
事实证明,vue-resource模块未正确发送数据或未正确接收数据;因此,当我尝试解析请求表单时,出现了一个错误,导致了该问题,并且浏览器假定原点已被阻止,尽管另有了解;但是,我现在正在使用jQuery。有效