【问题标题】:How to convert a Raw body data request for an API to ajax request如何将 API 的原始正文数据请求转换为 ajax 请求
【发布时间】:2021-11-12 03:39:47
【问题描述】:

我目前正在使用邮递员发出推送正文数据的 API 请求。我可以使用“x-www-form-urlencoded”或“raw”来实现它。请参阅以下示例:

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

$.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)
}
});

任何帮助将不胜感激

【问题讨论】:

  • 您明确将其作为 JSON 发送,这是您不想要的。一个非常通用的 $.ajax 调用应该可以工作。删除headers 部分并使用data: { grant_type: "client_credentials", ...}

标签: javascript jquery ajax postman


【解决方案1】:

这里不匹配,因为您将 Content-Type 标头设置为 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)
  }
});

如果您想使用表单编码字符串,请执行以下操作:

$.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 处理程序的第一个参数不是您的示例所期望的请求或响应数据。我已经修改了那部分以接受正确的论点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2015-10-06
    • 2016-10-10
    相关资源
    最近更新 更多