【问题标题】:javascript fetch is not posting to rest api endpoint while postman is doing当邮递员正在做时,javascript fetch 没有发布到 rest api 端点
【发布时间】:2018-09-07 05:17:12
【问题描述】:

我有一个rest api endpoint,并且我正在使用POSTMAN 进行检查,该POSTMAN 发布正确。但是,当我使用 JAVASCRIPT FETCH 进行操作时,我无法发布它。以下是我的获取代码:

const { inputAOI, wktForCreation } = this.state

fetch('http://192.168.1.127:8080/aoi/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ userName: 'fuseim', aoiName: inputAOI, wkt: wktForCreation }),
      mode: 'no-cors'
    }).then(function (response) {
      if (response.ok) {
        return response.json()
      } else {
        throw new Error('Could not reach the API: ' + response.statusText)
      }
    }).then(function (data) {
      console.log({ data })
    }).catch(function (error) {
      console.log({ error })
    })

下面是请求标头的图像。

从上图中可以看出,在Request Headers 中,Content-Type 仍然是text/plain,但我正在发送application/json,如上图所示。

检查控制台中的响应预览。

以下是正确的 POSTMAN 请求:

【问题讨论】:

标签: javascript jquery fetch fetch-api


【解决方案1】:

正如 cmets 中所暗示的,问题出在 mode:"no-cors"

Content-Type 被认为是一个简单的标头,应该允许没有 cors,只能使用以下值:

  • application/x-www-form-urlencoded
  • 多部分/表单数据
  • 文本/纯文本

见:https://fetch.spec.whatwg.org/#simple-header

如果您在与脚本相同的主机/端口上运行 API,则应使用 mode: "same-origin" 或者将运行脚本的主机/端口添加为 API 上的允许来源。

有关 CORS 的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

【讨论】:

    【解决方案2】:

    代替

    headers: { 'Content-Type': 'application/json' }

    你可以试试:

    headers: new Headers({ 'Content-Type': 'application/json' })

    【讨论】:

    • 两者是等价的,结果是一样的
    猜你喜欢
    • 2019-04-24
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2022-01-25
    • 2021-02-11
    相关资源
    最近更新 更多