如何将 API 的原始正文数据请求转换为 ajax 请求

How to convert a Raw body data request for an API to ajax request

我目前正在使用 postman 发出 API 推送正文数据的请求。我可以使用“x-www-form-urlencoded”或“raw”让它工作。请参阅以下示例:

我正在尝试将其转换为 ajax javascript 请求,但不确定如何设置 body/data 文本的格式。这是我的脚本:

$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
headers: {
"Content-Type": "application/json"
},
data: {

 " grant_type=client_credentials
&client_id=***
&client_secret=***
&resource=https://analysis.windows.net/powerbi/api "



},
success: (data) => {
console.log(data.token)
},
error: (data) => {
console.log('rr', data)
}
});

如有任何帮助,我们将不胜感激

此处不匹配,因为您将 Content-Type header 设置为 JSON,但您发送 form-urlencoded。您需要始终如一地使用其中之一。

如果您想明确使用 JSON,请执行以下操作:

$.ajax({
  type: 'POST',
  url: 'https://login.microsoftonline.com/***/oauth2/token',
  contentType: 'application/json', // shorter than setting the headers directly, but does the same thing
  data: JSON.stringify({
    grant_type: 'client_credentials',
    client_id: '***',
    client_secret: '***'
    resource: 'https://analysis.windows.net/powerbi/api'
  }),
  success: data => {
    console.log(data.token)
  },
  error: (xhr, textStatus, error) => {
    console.log('rr', error)
  }
});

如果您想使用 form-urlencoded 字符串,请执行以下操作:

$.ajax({
  type: 'POST',
  url: 'https://login.microsoftonline.com/***/oauth2/token',
  data: 'grant_type=client_credentials&client_id=***&client_secret=***&resource=https://analysis.windows.net/powerbi/api',
  success: data => {
    console.log(data.token)
  },
  error: (xhr, textStatus, error) => {
    console.log('rr', error)
  }
});

请注意,在上面的示例中,error 处理程序的第一个参数不是您的示例所期望的请求或响应数据。我已经修改了那部分以接受正确的参数。