2016-09-30 97 views
1

我有一个场景,我正在执行到快速服务器的提取请求。快递服务器然后执行对api 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的响应状态,但是在t他的客户端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; 
    }); 
}; 

回答

0

调试我发现我必须手动设置状态代码在服务器端的承诺.catch

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.status(error.response.status); // <-- HERE --- 
    res.json(error.response); 
    }); 
}); 

否则后,它正在返回一个200,这很奇怪,因为error.response是一个状态为422的对象,并且checkStatus函数会检查它。也许我误解表演时什么是真正发回res.json()

它没有任何意义,我虽然因为手动设置状态之前,我有以下陷阱:

.catch(error => { 
     res.json(error.response); 
    }); 

和2台.logs:

export const checkStatus = response => { 
    console.log(response.status); 
    console.log(response); 

这些正在返回:

{... status:200,statusText:'OK'...}

和所有我至今变化是这样的:

.catch(error => { 
    res.status(error.response.status); 
    res.json(error.response); 
}); 

,现在它记录:

{...状态:422,状态文本:“我的自定义状态文本'...}

我不'不明白为什么只改变res.status也会更新响应对象本身...