React Native - Fetch POST请求被发送为GET请求

25

我在使用FETCH时遇到了问题。

我正在尝试在react-native中使用FETCH进行POST请求。

    fetch("http://www.example.co.uk/login", {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: 'test',
            password: 'test123',
        })
    })

        .then((response) => response.json())
        .then((responseData) => {
            console.log(
                "POST Response",
                "Response Body -> " + JSON.stringify(responseData)
            )
        })
        .done();
}

当我使用Charles检查此调用时,它被记录为GET请求,并且应该在正文中的用户名和密码不在那里。

enter image description here

有人能帮忙解决这个问题吗?


12个回答

11

我遇到了一个问题,当POST请求发送到HTTPS服务器时(而不是HTTP),它会在某个地方被转换为GET请求。

结果发现我的错误在于将请求发送到 http://myserver.com:80 而不是 https://myserver.com:443。一旦我更正了前缀和端口,这个请求就能正确地以POST方式发送。


发生了同样的事情。 - Dan Field
1
当POST被重定向(在我的情况下是从http到https),它会被转换为GET(这有什么逻辑??)。在我的情况下,https请求完美地工作,而不需要将端口附加到域名后面! - WiRa
似乎这是几乎所有浏览器中都存在的糟糕实现的功能:https://serverfault.com/questions/434205/nginx-https-rewrite-turns-post-to-get - WiRa

10

这对我有用:

let data = {
  method: 'POST',
  credentials: 'same-origin',
  mode: 'same-origin',
  body: JSON.stringify({
    appoid: appo_id
  }),
  headers: {
    'Accept':       'application/json',
    'Content-Type': 'application/json',
    'X-CSRFToken':  cookie.load('csrftoken')
  }
}
return fetch('/appointments/get_appos', data)
        .then(response => response.json())  // promise
        .then(json => dispatch(receiveAppos(json)))
} 

这里的cookie是什么? - red-devil

6
使用FormData。问题在于JSON.stringify。您可以直接导入,它不是第三方。
import FormData from 'FormData';
...
var data = new FormData();
data.append("username", "ABCD");
data.append("password", "1234");
fetch('YOUR_URL', {
method: 'POST',
headers: {
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data',
},
body:data,
})
.then((response) => response.json())
.then((responseJson) => {
    console.log('response object:',responseJson)
})
.catch((error) => {
  console.error(error);
});

3
我遇到过同样的问题。你需要将对象赋值,不确定原因。
让我们看一下代码:
``` let options = {}; options.body = formdata; options.header = header; options.method = 'post'; ```
这部分代码设置了一个选项对象,其中包含三个属性:body、header和method。请注意,这里使用的是对象赋值。
希望这能够帮助您解决问题。

1
这毫无意义。这将导致完全相同的对象。 - Tieme
也许它与ES6的新特性发生了冲突?http://www.2ality.com/2011/11/keyword-parameters.html - Kokizzu
我也在一个应用程序中看到了这个问题,该应用程序直接在fetch函数中定义为参数,而不是在另一个应用程序中我像这样定义对象 --- let options = Object.assign( {method: verb}, requestParams ? {body: JSON.stringify(requestParams)} : null, {headers: headers} ); --- 所以看起来这是正确的答案! - WiRa
根据 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 的说法,应该可以将对象定义为参数...或者这可能是iOS特定的问题吗? - WiRa

3

2
如果您想使用fetch进行POST请求,可以按以下方式操作。
        fetch('url?email=a@gmail.com&password=a@gmail.com', {
             method: 'POST'
          })
          .then((response) => response.json())
          .then((responseJson) => {
             console.log(responseJson);
             // this.setState({
             //    data: responseJson
             // })
          })
          .catch((error) => {
             console.error(error);
          });

如何使用POST方法在ListView中显示Json数据? - Abhi
将 JSON 转换为数组并循环它。 - Ryosuke Hujisawa
非常感谢你,兄弟 @Ryosuke - Abhi
兄弟,你能帮忙吗?请看下面的链接:https://stackoverflow.com/questions/54764351/how-to-display-json-data-on-listview-react-native-by-post-request-api - Abhi
你好,能否帮助我解决这个问题,链接为 https://stackoverflow.com/questions/54801602/how-to-generate-dynaimc-ui-on-json-response-react-native ... 因为我卡住了,不知道该怎么做。谢谢。 - Abhi

1
重定向URL会将POST请求转换为GET请求。(不知道为什么) 因此,请确保添加任何尾随箭头。 例如:"http://www.example.co.uk/login/"

0

这对我有用!


 const params = {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        id: '1',
        name: 'user',
        age: '26',
      
      }),
    };
    fetch('https://yourapi/', params)
      .then(response => response.json())
      .then(data => console.log(data));

0

我已经做了一些更改并进行了测试,对我来说运行良好,请查看以下所有更改:

 constructor(props) {
    super(props);
    this.state = { isLoading: true};
    this.getRemoteData();
 }

getRemoteData = () => {

fetch('http://www.example.co.uk/login', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: 'test',
                password: 'test123',
            })
        })

            .then((response) => response.json())
            .then((responseData) => {
                console.log("RESULTS HERE:", responseData)

            this.setState({
          isLoading: false,
          dataSource: responseJson,
        }, function(){

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

0

与Rishijay的答案类似,我的问题是由于JSON.stringify未能正确转换POST请求的主体。

我解决这个问题的方法是使用search-params节点模块中的build来使其正常工作。 我的fetch内容的主体如下:body: build({...})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接