harsh
harsh

Reputation: 114

API not fetching any response even for status 200 in react(Fetch API)

I am integrating an API with my react login form, but I am getting this error, even for the status code 200:

Failed to load response data: No data found for a resource with given identifier .

When I fired the API in Postman everything was working fine but when I integrate it with my application it is showing error:

index.js:1 Error: SyntaxError: Unexpected end of input

let userLogIn = async function() {
        fetch('http://kishansharma.pythonanywhere.com/login', {
            method: 'POST', 
            mode: 'no-cors', 
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `email=${emailId}&password=${password}`,
        })
        .then(response => response.json())
        .then((data) => {
        console.log('Success:', data);
        })
        .catch((error) => {
        console.error('Error:', error);
        });
    }

I have added the code where I am integrating the API, any help will be appreciated.

Upvotes: 0

Views: 4673

Answers (2)

Mouli
Mouli

Reputation: 1

I had the same kind of error i fixed it by adding e.preventDefault();

before:

const handleSubmit = () => {
       axios
      .post("http://localhost:5000/users", {name: ""})
      .then((res) => console.log(res.data))
      .catch((err) => console.log(err.message));
  };

correction:

const handleSubmit = (e) => {
    e.preventDefault();
    axios
      .post("http://localhost:5000/users", {name: ""})
      .then((res) => console.log(res.data))
      .catch((err) => console.log(err.message));
  };

Upvotes: -1

christian wuensche
christian wuensche

Reputation: 1043

The Error SyntaxError: Unexpected end of input usually comes from invalid json response. Maybe Postman shows you the raw response as text. You should check if the response is valid json with no syntax failurs.

Things to try:

  • In your headers object add the following: Accept': 'application/json'
  • Is the response realy valid JSON? Sometimes ther is a missing }

Upvotes: 1

Related Questions