最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: Failed to fetch - react js - Stack Overflow

programmeradmin2浏览0评论

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

TypeError: Failed to fetch

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.

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

TypeError: Failed to fetch

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.

Share Improve this question asked Mar 25, 2018 at 15:42 S.M_EmamianS.M_Emamian 17.4k40 gold badges154 silver badges273 bronze badges 3
  • Can you try using the raw body option in postman, since it is closer to the code you have posted: – Daniel Stoyanoff Commented Mar 25, 2018 at 15:46
  • I got responsive. – S.M_Emamian Commented Mar 25, 2018 at 15:48
  • Why I got down vote?! – S.M_Emamian Commented Mar 25, 2018 at 15:48
Add a ment  | 

2 Answers 2

Reset to default 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

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.

发布评论

评论列表(0)

  1. 暂无评论