request` 请求成功但使用 `axios` 失败"/>
使用 `request` 请求成功但使用 `axios` 失败
我有这个微软图形身份验证代码,使用
axios
然后使用request
发出我认为是相同的请求。但是axios请求失败,返回404,而request请求成功。我对 axios 做错了什么?
const axios = require('axios')
const request = require("request");
const FormData = require('form-data');
const data = FormData()
data.append('client_id', XXXXXXXXXXX),
data.append('client_secret', XXXXXXXXX),
data.append('scope', "/.default"),
data.append('grant_type', 'client_credentials')
const requestParams = {
client_id: logins.activedirectory.clientID,
client_secret: logins.activedirectory.clientSecret,
scope: "/.default",
grant_type: "client_credentials",
};
const endpoint = "/" + XXXXXXXX + "/oauth2/v2.0/token";
///////// AXIOS //////////
axios({
method: 'post',
url: endpoint,
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
///////// REQUEST /////////
request.post({ url:endpoint, form: requestParams }, function (err, response, body) {
if (err) {
console.log(err);
} else {
console.log(body);
}
});
回答如下:
这是一个老问题,但我最近遇到了类似的问题,经过一番研究后解决了。客户端凭据 API 需要一个 url_encoded 正文。 这记录在这里:https://learn.microsoft/en-us/graph/auth-v2-service。
form-data
包并没有完全正确地做到这一点。相反,您需要将身体构建为一个对象,然后对其进行字符串化和 url 编码。之前和之后看起来像这样:
const postData = {
tenant: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
client_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
scope: "https://graph.microsoft/.default",
client_secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
grant_type: "client_credentials",
};
和 stringifed 和 urlencoded
tenant=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
&scope=https%3A%2F%2Fgraph.microsoft%2F.default
&client_secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
&grant_type=client_credentials
qs 包很容易做到这一点。参考这篇文章https://askfiqri/how-to-get-an-access-token-for-microsoft-graph-api-using-node-js-258723f29cc6
完整的解决方案是:
const axios = require("axios");
const qs = require("qs");
const postData = {
tenant: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
client_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
scope: "https://graph.microsoft/.default",
client_secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
grant_type: "client_credentials",
};
const OAUTH_URL = `https://login.microsoftonline/${postData.tenant}/oauth2/v2.0/token`;
let response = await axios({
method: "post",
url: OAUTH_URL,
data: qs.stringify(postData),
headers: { "Content-Type": "application/x-www-form-urlencoded" },
});
然后做你喜欢的回应
注意:此 api 调用必须从服务器或通过代理完成(在我的例子中是通过 APIGateway 的 AWS Lambda)。由于 CORS 错误,axios 调用将无法从浏览器运行,这显然无法规避。
更多推荐
使用 `request` 请求成功但使用 `axios` 失败
发布评论