【问题标题】:Set one of the angular HTTP data variables to a boolean将 Angular HTTP 数据变量之一设置为布尔值
【发布时间】:2016-11-21 18:26:07
【问题描述】:

编辑:这可能是后端 API 的问题吗?通过 $.param 发送的数据请求总是字符串,对吗?所以他们需要在后端解析这些东西?

我目前正在尝试向 API 发送发布请求以注册用户。其中一项要求是接受条款和条件以及年龄要求,它需要一个布尔值。

我认为问题可能是 $http 请求正在向 API 后端发送一个字符串而不是布尔值,因此它拒绝了它。如何通过 $http 发送布尔值?

    var apiCall = {
      method: 'POST',
      url: 'API_URL',
      data: $.param({
        'user[email]': username,
        'user[password]': password,
        'user[password_confirmation]':password,
        'profile[age_acceptance]': ageAcceptance,
        'profile[terms_acceptance]': termsAcceptance
      }),
      headers: {
        'Accept': 'application/vnd.softswiss.v1+json',
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      transformRequest: function(data, headersGetter, status) {
        console.log(data);
        console.log(headersGetter(data));
      }
    }

【问题讨论】:

  • 尝试使用 console.log 语句(或开发工具调试器)查看 typeof termsAcceptance 返回的内容。然后你就会确定这是否是类型的问题。
  • 已经完成。传递给 $.param 的值是布尔值——但是当我记录转换请求时,它只是一个大字符串(这可能是正常的,但我只是想弄清楚为什么我会被 API 拒绝)。
  • 您的 API 是否接受 'Content-Type': 'application/json' 而不是 x-www-form-urlencoded
  • 不使用jQuery参数编码器,而是使用$httpParamSerializer serviceDEMO on JSFiddle
  • 这个好像和$.param功能一样,有什么优势呢? (没有解决问题,只是好奇)。

标签: angularjs post


【解决方案1】:
var dataToPost = JSON.stringify( {
    'user[email]': username,
    'user[password]': password,
    'user[password_confirmation]':password,
    'profile[age_acceptance]': ageAcceptance,
    'profile[terms_acceptance]': termsAcceptance
  });

  data: dataToPost,
  headers: {.......,
   .....

你必须给你的参数设置字符串。

JSON.stringify(params)

【讨论】:

  • 修改 API 调用如下:错误消息现在显示电子邮件无效。不确定这是正确的解决方案。数据: $.param({ 'user[email]': JSON.stringify(username), 'user[password]': JSON.stringify(password), 'user[password_confirmation]': JSON.stringify(password), ' profile[age_acceptance]': JSON.stringify(ageAcceptance), 'profile[terms_acceptance]': JSON.stringify(termsAcceptance) }),
  • 因此,api 需要这样的响应:“user%5Bemail%5D=a%40b.x&user%5Bpassword%5D=test1234&user%5Bpassword_confirmation%5D=test1234&profile%5Bage_acceptance%5D=true&profile%5Bterms_acceptance %5D=true" 当我按照你的方式做时,我会这样:"{"user[email]":"a@b.c","user[password]":"test1234","user[password_confirmation]" :"test1234","profile[age_acceptance]":true,"profile[terms_acceptance]":true}" 我想我不能使用 JSON.stringify 因为 API 需要一个大字符串......但如果它想要一个布尔值,我不确定 $.param 会发送除字符串之外的任何内容。嗯。
猜你喜欢
  • 2017-11-05
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
相关资源
最近更新 更多