React Native - Fetch POST request is sending as GET request

后端 未结 11 1099
感情败类
感情败类 2020-12-16 14:52

I\'m having issues when using FETCH.

I am trying to make a POST request using FETCH in react-native.

    fetch(\"http://www.example.co.uk/login\", {
         


        
相关标签:
11条回答
  • 2020-12-16 15:41

    If you wanna do POST request using fetch, You can do like that

            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);
              });
    
    0 讨论(0)
  • 2020-12-16 15:46

    Redirection of url converts the POST request into GET requests.(Don't know why) So make sure of adding trailing arrows if any. like :"http://www.example.co.uk/login/"

    0 讨论(0)
  • 2020-12-16 15:47

    Use FormData. Problem is with JSON.stringify. You can directly import, its not third party

    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);
    });
    
    0 讨论(0)
  • 2020-12-16 15:47

    Similar to Rishijay's answer, my issue was with JSON.stringify not properly converting the body of POST request.

    The way I solved this was using build from the search-params node module to make it work. My fetch contents had body like this body: build({...})

    0 讨论(0)
  • 2020-12-16 15:48

    In my case, the redirect was caused by wrongly formed url for the POST request: http://localhost:90/Worx/drupal/d8/www//jsonapi double slash before jsonapi

    Because of the wrong url, the browser was redirecting the request and changing the method from POST to GET.

    I was able to debug it after reading this: https://serverfault.com/questions/434205/nginx-https-rewrite-turns-post-to-get

    0 讨论(0)
提交回复
热议问题