我正在尝试通过使用axios向api请求来获得授权令牌:
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
auth: {
username: usr,
password: pwd
}
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})
我总是得到状态码401(未经授权):
Error: Request failed with status code 401
我在哪里做错了?
事实是使用python发出相同的请求可以正常工作:
payload = "username=%s&password=%s" % (usr,pwd)
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.request("POST", url_login, data=payload, headers=headers)
print(response.text)
data = response.json()
token = data["token"]
答案 0 :(得分:0)
通过在axios的auth: {}
中发送用户名和密码,您就可以进行基本身份验证,基本上是发送Authorization: basic <base64(user:pass)>
标头。
根据有效的python程序,您需要发送用户名和密码作为请求正文的一部分。您还需要为url编码的内容类型序列化正文参数。
例如
const querystring = require('querystring');
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: querystring.stringify({
username: usr,
password: pwd
})
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})