我正在创建一个基于Flask的API(扩展有flask-restful)和一个Vue.js的前端应用程序。
这两者现在都在localhost上运行。
flask: 127.0.0.1:5000
,
vue: localhost:8080/
我使用axios调用API。 第一次调用导致CORS错误,因此我安装了flask-CORS扩展名,并且CORS错误消失了。
在API方面,可以通过GET方法调用URL http://127.0.0.1:5000/signin
,并且需要基本身份验证授权。如果验证数据有效,则返回令牌。在邮递员中,这很好用。在我的Vue.js应用程序中,通过axios调用API,如下所示:
signIn() {
const session_url = 'http://127.0.0.1:5000/signin'
axios.get(session_url, {}, {
auth: {
username: this.email,
password: this.password
}
}).then(response => {
console.log('Authenticated')
console.log(response.data)
/*this.$store.dispatch('signin', response.data)*/
}).catch(error => {
console.log('Error on Authentication')
this.error = error
console.log(error)
});
}
...浏览器中的控制台抛出: Error: "Request failed with status code 401"
。
在Postman中,API调用可以正常工作,也可以使用CURL:
curl -u Hans:testing -i -X GET http://127.0.0.1:5000/signin
返回
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 180
Access-Control-Allow-Origin: *
Server: Werkzeug/0.14.1 Python/3.6.4
Date: Sat, 22 Sep 2018 14:22:37 GMT
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...."
}
为什么通过axios调用api时会出现401错误?
感谢您的帮助!
答案 0 :(得分:0)
您传递参数的方式不正确。请看下面的代码。在get调用中,参数在params对象中传递。
axios.get(session_url, {params : {username: 'x', password:'y'}}).then()
答案 1 :(得分:0)
我有两个步骤可以帮助您。
步骤1:
将日志请求打印到您的API http://127.0.0.1:5000/signin
中,以查看帖子中的结果,例如:
from flask import request
@app.route('/signin', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
第2步:
从您的API检查状态响应:
signIn() {
//check code
console.log("email",this.email);
console.log("pass", this.password);
const session_url = 'http://127.0.0.1:5000/signin'
axios.get(session_url, {}, {
auth: {
username: this.email,
password: this.password
}
}).then(response => {
console.log(response);
//console.log('Authenticated')
//console.log(response.data)
/*this.$store.dispatch('signin', response.data)*/
}).catch(error => {
console.log('Error on Authentication')
this.error = error
console.log(error)
});
}
答案 2 :(得分:0)
好的,我找到了解决方案,但是我不太确定为什么这行得通。
this.email
和this.password
通过v-model
指令从表单获取其值,并将其保存在data()对象中。因此,我想通过axios调用api时,状态不会保存。因此,当我将this.email
和this.password
的值写入新变量,然后再将它们传递给axios时,来自的值将被传输并且请求有效。
毕竟,这不是axios的问题,而是我对Vue.js的工作原理缺乏了解。
signIn() {
const session_url = 'http://127.0.0.1:5000/signin'
var username = this.email
var password = this.password
axios({
method: 'get',
url: session_url,
auth: {
username: username,
password: password
}
})
.then(response => {
console.log('Authenticated')
console.log(response.data)
/*this.$store.dispatch('signin', response.data)*/
}).catch(error => {
console.log('Error on Authentication')
this.error = error
console.log(error)
});
}
答案 3 :(得分:0)
也请检查以下内容:
.catch(error => {
console.log(error.response.data);
});
就在这里,您可以从api中找到响应消息。