1
fetch('http://3.108.170.236/erp/apis/login_otp.php', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    monumber: '8770276989',
  }),
})
  .then(async response => {
    console.log('fetching api');
    console.log(await response.json());
    return await response.json();
  })
  
  .catch(err => {
    console.log('fetch error' + err);
  });

postman api output

[{"otp_value":665354,"student_id":"3117"}]

getting error of 405 method not allowed. i am sending data in post format with plain text and api response is in json what should i do get proper value.

Thanking you advance community.

user3840170
  • 26,597
  • 4
  • 30
  • 62
manoj pali
  • 33
  • 6

1 Answers1

0

Make these changes in your headers object.

  • To send plain text, set Content-Type to application/x-www-form-urlencoded.
  • To receive JSON type data set Accept to application/json. Of course, you have to be certain that the server is sending back a JSON response otherwise you will get a syntax error when parsing it on the client side.

headers object:

headers: {
    Accept: 'application/x-www-form-urlencoded',
    'Content-Type': 'application/json',
} 

If you are not sure that the response will be in JSON or plain text, you can check the response's header content-type property before acting on it:

(This is a modification of the answer here to fit your question)

...

.then(response => { 
    console.log('fetching api');

    const contentType = response.headers.get("content-type"); 

    // This is JSON type response
    if (contentType && contentType.indexOf("application/json") !== -1) {
        return response.json().then(data => {
            // The response was a JSON object
            // Process your data as a JavaScript object
        });
    } else {
        return response.text().then(text => {
            // The response wasn't a JSON object
            // Process your text as a String
        });
    }
})
// All errors can be caught here.
.catch((err) => console.log("The error:", err));

...
Chizaram Igolo
  • 907
  • 8
  • 18