我正在编写Fetch请求,以将新用户发布到应用程序。提取与redux存储集成在一起。响应返回[object Object],而response.status返回undefined。我是Redux的新手,并且想知道错误是否在那儿。这是我的动作创建者文件中的代码:
export function createCustomerSuccess(values) {
return {
type: types.CREATE_CUSTOMER_SUCCESS,
values: values
};
}
export function createCustomer(values) {
return function (dispatch, getState) {
console.log('values passing to store', values);
return postIndividual(values).then( (response) => {
console.log('calling customer actions');
console.log(response);
if(response.status === 200){
console.log(response.status);
dispatch(createCustomerSuccess(values));
console.log('create customer success');
}
else {
console.log('not successful');
}
});
};
}
function postIndividual(values) {
console.log('test from post' + JSON.stringify(values));
const URLPOST = "http://myurlisworking/Add";
return fetch (URLPOST, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Access-Control-Origin": "*"
},
body: JSON.stringify(values)
})
.then(response => response.json())
.then(response => {
console.log('response' + response.status)
});
}
答案 0 :(得分:1)
问题似乎符合您的期望。当您的第一个.then
在fetch()
之后被调用时,您就可以在那里response.status
进行检查。
您可以像下面那样重写您的抓取,然后看能否解决。
function postIndividual(values) {
console.log('test from post' + JSON.stringify(values));
const URLPOST = "http://myurlisworking/Add";
return fetch (URLPOST, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Access-Control-Origin": "*"
},
body: JSON.stringify(values)
})
.then(response => {
console.log('response' + response.status)
return response.ok && response.json();
})
.catch(err => console.log('Error:', err));
}
您可以在此处检查response.status
^,然后执行您想要的操作。
或者,您可以只在fetch
中执行postIndividual
,而在createCustomer
中处理响应。