【问题标题】:iron-ajax not support content-type='application/json' for POST requestIron-ajax 不支持 POST 请求的 content-type='application/json'
【发布时间】:2017-09-18 12:49:10
【问题描述】:

我正在尝试使用 iron-ajax,但 content-type='application/json' 不支持。

<iron-ajax id="ajaxRequestOtp"
                               method="POST"
                               url="[[apiEndPoint]]/user-sms-auth"
                               body="{{requestOtpBody}}"
                               handle-as="json"
                               headers='{"Accept": "application/json"}'
                               on-response="_responseRequestOtp"
                               on-error="_errorResponseRequestOtp"
                               content-type='application/json'>
                    </iron-ajax>

财产-

static get properties() {
            return {
                apiEndPoint: {
                    type: String,
                    value: 'http://example.com'
                },
                requestOtpBody: {
                    type: String,
                    computed: '_createRequestOtpBody(mobileNumber)',
                    notify: true
                }
            };
        }

计算函数 -

_createRequestOtpBody(mobileNumber) {
            let body = {
                phone_number: "+91" + mobileNumber
            }
            return JSON.stringify(body);
        }

这不起作用,404 错误请求。我需要向我的服务器发送一个 JSON 对象。

错误信息-

OPTIONS http://example.com/user-sms-auth 404 (Not Found)
(index):1 Failed to load http://example.com/user-sms-auth: Response for preflight has invalid HTTP status code 404

【问题讨论】:

  • iron-ajax 支持 content-type for POST,并且确实发送带有标头集的 JSON 数据:demo。有400的详细信息吗?是否有指示请求问题的错误消息? (例如,它是否缺少标题?格式错误的正文?等等)
  • @tony19 - 我只是用 codepen //httpbin.org/post 中提供的 url 替换我的 url 并保持所有其他内容相同,它开始工作了。所以你认为问题出在我的后端服务器吗???
  • 您将收到的错误代码从“400 Bad Request”更改为“404 Bad Request”,这是不正确的,因为 404 是“未找到”。如果您收到 400,则表示您的请求有问题。 404 表示您请求的资源不存在(即错误的 URL)。

标签: json polymer polymer-2.x iron-ajax


【解决方案1】:

制作requestOtpBody => type: Object,并跳过JSON.stringify这一步。

_createRequestOtpBody(mobileNumber) {
    return { phone_number: "+91" + mobileNumber };
}

【讨论】:

  • @rahul 你试过将with-credentials 添加到iron-ajax 元素吗?
猜你喜欢
  • 2013-04-15
  • 2011-08-11
  • 2018-02-28
  • 2015-10-20
  • 1970-01-01
  • 2022-11-11
  • 2020-11-14
  • 1970-01-01
  • 2012-09-11
相关资源
最近更新 更多