Postman 可以工作,但 Fetch 不行。怎么了?

Posted

技术标签:

【中文标题】Postman 可以工作,但 Fetch 不行。怎么了?【英文标题】:Postman works but Fetch doesn't.what's wrong? 【发布时间】:2019-05-13 12:48:46 【问题描述】:

我无法从 JSON 获取信息。 这是我的代码:

    fetch('http://fruitmruit.com/webservice/products/details', 
      method: 'POST',
      headers: 
        Accept: 'application/json',
        'Content-Type': 'application/json',
      ,
      body: JSON.stringify(
        product : '145',
      ),
    ).then((response) => response.json())
    .then((responseJson) => 
      console.log(responseJson)
      this.setState(
        loading: false,

      , function()

      );
    )
    .catch((error) => 
      console.error(error);
    );


问题是我在 console.log() 中得到status : "error"

但在 Postman 中获取 status : "ok":

也许问题是 url 中的“http”? 感谢您阅读我的问题。

【问题讨论】:

您是否检查了请求中145 的类型?但为此我认为它应该返回Error:400 是的,我用过:'145' & 145 & "145" 但它们都不起作用 使用'Content-Type': 'application/x-www-form-urlencoded' 而不是'Content-Type': 'application/json' 或者尝试以app/json 格式发送原始数据并尝试 尝试通过在 postman 中单击 Cookies 选项旁边的 Code 来验证您在 fetch 中的参数 @Vinil Prabhu,试过这个但没用。 :( 【参考方案1】:

由于 body 类型被接受为 x-www-form-urlencoded 放内容类型

application/x-www-form-urlencoded

和 body 作为简单的字符串 所以fetch函数变成如下图

test()
    console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.');
    fetch('http://fruitmruit.com/webservice/products/details', 
      method: 'POST',
      headers: 
        'Content-Type': 'application/x-www-form-urlencoded',
      ,
      body: 
        'product=145'
      ,
    ).then((response) => response.json())
    .then((responseJson) => 
      console.log('response>>>>>>>>>>>>>>>>>'+ JSON.stringify(responseJson))

    )
    .catch((error) => 
      console.error('>>>>>>>>>>>>>>>'+error);
    );


【讨论】:

编辑答案,这将无缝工作。 @MohsenSedaghatFard 哦。终于你救了我,非常非常非常感谢@Pramod

以上是关于Postman 可以工作,但 Fetch 不行。怎么了?的主要内容,如果未能解决你的问题,请参考以下文章