我正在尝试使用 Axios 请求 API:
const axios = require ("axios")
const httpsAgent = require('https-agent')
const https = require('https')
const instance = axios ({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
auth: {
username: 'username'
}
})
axios.post("url_api").then(function(response){
console.log(response.data)
}).then(function(response){
console.log(response.data)
}).catch((e)=>{console.log(e)})
但它显示错误 401:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string
response: {
status: 401,
statusText: 'Unauthorized',
...
},
data: 'Unauthorized'
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
还有什么配置要做吗?失眠/邮递员作品
答案 0 :(得分:1)
axios.post("url_api",body,header)
答案 1 :(得分:0)
你在这里的代码
const instance = axios ({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
auth: {
username: 'username'
}
})
它已经等同于发起一个请求,但问题是你没有传递强制性的 url
和 method
参数
所以修改为
const request = axios ({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
method: 'post',
url: 'your_api_url_here', // important change
auth: {
username: 'username'
}
})
或者你可以简单的跟着做
axios.post('url_here', data );
最后,你的代码必须是这样的
const instance = axios({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
auth: {
username: 'username'
},
method: 'post',
url: 'your_api_url_here',
})
.then(response => console.log(response.data))
.catch((e) => console.log(e));
选择其中之一,但不要同时选择。