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

I want to send data to my sever but I got this error:TypeError: Failed to fetchmy codes:function login(

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744662234a4586530.html

相关推荐

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

    I want to send data to my sever but I got this error:TypeError: Failed to fetchmy codes:function login(

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>