我正在尝试通过使用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"]
通过在axios中的auth: {}
发送用户名和密码,您正在进行基本身份验证,基本上发送Authorization: basic <base64(user:pass)>
标头。
根据工作的python程序,您需要发送用户名和密码作为请求正文的一部分。您还需要为url编码的内容类型序列化身体参数。
EG
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)
})