POST 请求与 Postman 一起使用但无法获取? [英] POST Request works with Postman but fails in fetch?

查看:74
本文介绍了POST 请求与 Postman 一起使用但无法获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了后端,它将接受对以下网址的请求

<块引用>

http://10.1.0.1/cgi-bin/api/write_config

使用 Postman 我得到了适当的响应,但是当我用 fetch 尝试同样的事情时,我得到一个网络错误

这是我的代码:

<预><代码>获取('http://10.1.0.1/cgi-bin/api/write_config',{方法:'POST',标题:{'内容类型':'应用程序/json',},正文:JSON.stringify({参数 1: '属性 1',参数 2: '属性 2',参数 3: '属性 3',}),}).then(响应 => {控制台日志(响应.json())返回 response.json()}).then(数据=> {控制台日志(数据)}).catch(e => {console.log('在 catch 块中')控制台日志(e)})

这些是我从响应中得到的标题(在 Postman 中):

内容类型:应用程序/json访问控制允许来源:*

我收到以下错误(在 Javascript 中):

<块引用>

{ [TypeError: Network request failed] 行:24117,列:31,
来源网址:'http://localhost:8081/index.delta?platform=android&dev=true&minify=false'}

我以与配置其他设备相同的方式配置了 Raspberry Pi,然后输出是正确的.是 Javascript 的证书问题吗?

解决方案

你试过 console.log(body) 了吗?有时 JSON 不起作用.如果你的身体没有问题.我确定标题是错误的

I created backend where it will accept requests to the following url

http://10.1.0.1/cgi-bin/api/write_config

With Postman I get the appropriate response but when I try the same thing with fetch, I get a network error

This is my code:


fetch ('http://10.1.0.1/cgi-bin/api/write_config', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          param1: 'attr1',
          param2: 'attr2',
          param3: 'attr3',
        }),
      })
      .then(response => {
        console.log(response.json())
        return response.json()
      })
      .then(data => {

        console.log(data)
      })
      .catch(e => {
        console.log('In catch block')
        console.log(e)
      })

These are the header I'm getting from the response (in Postman):

Content-Type: application/json Access-Control-Allow-Origin: *

I'm getting the following error (in Javascript):

{ [TypeError: Network request failed] line: 24117, column: 31,
sourceURL: 'http://localhost:8081/index.delta?platform=android&dev=true&minify=false' }

Edit:

I configured the Raspberry Pi in the same way in which I configured the other device then the output is correct. Is it some certificate issue with Javascript?

解决方案

did u tried console.log(body) ? sometimes JSON not work. if u don't have problem with body . I'm sure header is wrong

这篇关于POST 请求与 Postman 一起使用但无法获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆