2017-08-27 46 views
1

我試圖從反應的應用程序發佈到php後端(流明5.3)通過fetch api。流明API返回422錯誤時傳遞正文爲JSON

我的職務如下:

function login(userData, onError, cb) { 
    return fetch('/v1/auth/login', { 
    method: 'post', 
    body: JSON.stringify(userData), 
    headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json', 
    }, 
    }).then(checkStatus) 
    .then(parseJSON) 
    .then(cb) 
    .catch(onError); 
} 

其中userData是:

const userData = { 
    email: this.state.fields.username, 
    password: this.state.fields.password, 
}; 

但是我收到一個錯誤:

422 error

這將表明我的身體是不正確的?我懷疑這是因爲當我測試的郵遞員等效請求,並不會在人體內經過password我會收到一個422錯誤:

422 error in postman

這使我相信,身體也許不是正確格式化?

有點可疑的一個部分是,如果我從php後端記錄我的響應沒有返回正文。從理論上講,如果我的身體是格式不正確,我應該接受來自後端如下:

{ 
    "email": [ 
     "The email field is required." 
    ], 
    "password": [ 
     "The password field is required." 
    ] 
} 

回答

0

原來我流明API不接受JSON作爲身體。

的修復,現在是如下修改我的要求:

function login(userData, onError, cb) { 
    return fetch('/v1/auth/login', { 
    method: 'post', 
    body: serialize(userData), // no longer passing json 
    headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/x-www-form-urlencoded' // no longer passing json 
    }, 
    }).then(checkStatus) 
    .then(parseJSON) 
    .then(cb) 
    .catch(onError); 
} 

function serialize(obj) { 
    let str = []; 
    for(let p in obj) 
    if (obj.hasOwnProperty(p)) { 
     str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); 
    } 
    return str.join("&"); 
} 

其中userData是:

const userData = { 
    email: this.state.fields.username, 
    password: this.state.fields.password, 
}; 

,現在所有人都開心:)希望這有助於!