当从我的react / redux前端向我的API发送请求时,我遇到了一个问题。 API端点在“ api-key”标头中需要一个jwt令牌,但是,在尝试发送请求时,我收到JSON.parse错误eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVjMzMzNWJkZDY2NmM5MmYxMGQxMDU3MyIsInBlcm1pc3Npb25zIjowLCJ2IjowLCJpYXQiOjE1NDY4NTk5NjV9.WIL6vCO95BEV7DWbRMheAwIRRoYO3cQQbzPdIRVv4tI
。
我认为这是因为JWT的格式设置导致无法解析JSON,但是我无法将其包裹住。谢谢。
在创建后端时,我没有考虑这个问题,因此认为使用JWT作为api键会很好。理想情况下,我想继续使用此实现。
JWT的示例:export const getUserData = token => {
return async (dispatch, getState) => {
console.log(typeof token);
const response = await fetch("/api/user/data", {
method: "post",
headers: new Headers({
"Content-Type": "application/json",
"Accept": "application/json",
"api-key": token
})
});
const responseBody = await response.json();
console.log("Response JSON Body:", responseBody);
if (!response.ok) return dispatch({ type: AUTH_ERROR, payload: responseBody.message });
if (response.ok) return dispatch({ type: GET_USER_DATA, payload: responseBody });
};
};
获取请求:
pos
答案 0 :(得分:0)
正如@kemicofa在评论中所述,如果您的问题来自JSON.parse
,那么我们需要关注的是服务器响应,而不是您的服务器请求。
代码应准备就绪,可以接收来自服务器的错误响应并采取相应措施:
获取请求:
export const getUserData = token => {
return async (dispatch, getState) => {
console.log(typeof token);
const response = await fetch("/api/user/data", {
method: "post",
headers: new Headers({
"Content-Type": "application/json",
"Accept": "application/json",
"api-key": token
})
});
let responseBody;
try {
responseBody = await response.json();
} catch (e) {
responseBody = await response.text();
console.error('Server error response %s. json parse failed with error %s', responseBody, e.message)
return dispatch({ type: AUTH_ERROR, payload: responseBody });
}
console.log("Response JSON Body:", responseBody);
if (!response.ok) return dispatch({ type: AUTH_ERROR, payload: responseBody.message });
if (response.ok) return dispatch({ type: GET_USER_DATA, payload: responseBody });
};
};