2

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

3
  • Can you try using the raw body option in postman, since it is closer to the code you have posted: Commented Mar 25, 2018 at 15:46
  • I got responsive. Commented Mar 25, 2018 at 15:48
  • Why I got down vote?! Commented Mar 25, 2018 at 15:48

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.