S.M_Emamian
S.M_Emamian

Reputation: 17383

TypeError: Failed to fetch - react js

I want to send data to my sever but I got this error:

TypeError: Failed to fetch

enter image description here

my codes:

function login(username, password) {
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json','charset':'utf-8' },
        body: JSON.stringify({ 'username':username , 'password':password })
    };

    console.log(requestOptions);

    return fetch(BASE_URL+serverConstants.LOGIN_POST_REQUEST, requestOptions)
        .then(response => {
            if (!response.ok) {
                return Promise.reject(response.statusText);
            }

            return response.json();
        })
        .then(user => {
            // login successful if there's a jwt token in the response
            if (user && user.token) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('user', JSON.stringify(user));
            }

            return user;
        });
}

but I tested it on postman I got correct response.

enter image description here

Upvotes: 2

Views: 20365

Answers (2)

S.M_Emamian
S.M_Emamian

Reputation: 17383

If you want to send values to your sever like form-data from postman sowftware you should use formData (your don't need to import FormData from any class):

var formData = new FormData()
formData.append('yourKey, 'yourValue');

  var requestOptions = {
    method: 'POST',
    headers: {
        'Accept': 'application/json'
    },

    body: formData
};

return fetch('Your url', options)
    .then(checkStatus)
    .then(parseJSON);

of course from your server-side you should enable CORS. CORS depending on your language server-side is different.

Upvotes: 0

simbathesailor
simbathesailor

Reputation: 3687

Your preflight request is failing. Allow cross origin for the API you are hitting:

In node you do it like this,

res.header("Access-Control-Allow-Origin", "*");

Hope this helps

Upvotes: 1

Related Questions