【发布时间】:2017-02-09 09:30:47
【问题描述】:
我有一个场景,我正在向快速服务器执行获取请求。然后,快速服务器正在向 rails api 服务执行获取请求。所以我让客户端等待一个承诺解决,一旦服务器端承诺在与 rails api 通信后解决,该承诺就会解决。
在快递方面,我只会在服务器上的承诺解决后才调用res.json()。
服务器请求如下所示:
apiRouter.post('/login', (req, res) => {
const partnerId = 'id';
const apikey = 'key';
const apikeyIdentifier = 'id';
const cerebroUrl = `http://${apikeyIdentifier}:${apikey}@localhost:3000/v1/${partnerId}/login`;
const data = {
//data
};
httpRequest(cerebroUrl, httpMethods.post, data).then(response => {
res.json(response);
}).catch(error => {
console.log(error.response.status);
res.json(error.response);
});
});
和客户端请求:
const url = '/api/login';
const data = { username, password };
return httpRequest(url, httpMethods.post, data).then(response => {
console.log('success', response);
return response;
}).catch(error => {
console.error('error', error);
});
我有一个辅助方法可以在解决之前检查状态:
export const checkStatus = response => {
console.log(response.status);
console.log(response);
if (response.status >= 200 && response.status < 300) return response;
let error = new Error(response.statusText);
error.response = response;
throw error;
};
奇怪的是,在 checkStatus 方法中,控制台正在记录 200 以获取响应状态,但在客户端 request.then 中,响应却是 422。
我相信初始客户端请求首先解析为 200,但是当服务器承诺解析并且我得到 422 时,客户端已经过了那个阶段。或者什么...
有没有办法以更可预测的方式处理承诺?
获取请求函数如下所示:
export const httpRequest = (url, method, data) => {
return fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(data),
})
.then(checkStatus)
.then(parseJSON)
.then(response => {
return response;
});
};
【问题讨论】:
标签: javascript ruby-on-rails node.js fetch-api