react模板中request.js封装的fetch:如何为Spring后端处理json体中的错误
fetch wrapped in request.js in react boilerplate: how to handle error from json body for Spring backend
我正在尝试修改这个文件
https://github.com/mxstbr/react-boilerplate/blob/master/app/utils/request.js问题是它处理statusText中的errorMessage,这不是我可以从Spring后台设置的东西。
在响应的正文中有我的错误消息。
这是我目前为止解决它的方法
我已经尝试了许多不同的方法来使它工作,但我总是打破在这个提交中实现的逻辑:48eecac任何帮助将是感激的
import "whatwg-fetch";
import { fromJS } from "immutable";
/**
* Parses the JSON returned by a network request
*
* @param {object} response A response from a network request
*
* @return {object} The parsed JSON from the request
*/
function parseJSON(response) {
return response.json();
}
/**
* Checks if a network request came back fine, and throws an error if not
*
* @param {object} response A response from a network request
*
* @return {object|undefined} Returns either the response, or throws an error
*/
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
return response.json().then(throwError);
}
/**
* Throw an error with the errorMessage from the response body
*
* @param errorMessage
*/
function throwError(errorMessage) {
throw new Error(errorMessage);
}
/**
* Requests a URL, returning a promise
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
*
* @return {object} An object containing either "data" or "error"
*/
export default function request(url, options = {}) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON)
.then((response) => (response))
.catch((err) => ({ err }));
}
在react样板中遇到了同样的问题。基本上,它的工作方式是用来自响应的statusText头来构造Error,而不是响应的主体。
因此,为了在不修改样板代码的情况下处理自定义错误消息,您可以在发送响应的服务器端点的statusText头中直接编写自定义消息。
例如,在Express(4)中,您可以这样设置:
res.writeHead(401, 'My custom error message');
return res.send();
然后,在客户端处理错误的地方,你可以像这样访问这个自定义消息:
export function* handleError({ error }) {
console.log(error.message) // will output "My custom error message"
相关文章:
- 未能从后端触发javascript
- 检查浏览器'在asp.net的后端代码中启用或禁用了s JS
- Ajax登录技术(后端php)
- 将Rails后端添加到JS/HTML/CSS应用程序时,正确的文件位置是什么
- 视图没有't在模拟后端时加载
- 是否可以在不使用外部后端的情况下编写grafana数据源插件
- 如何将Angular 2用于各种网站&使用PHP作为后端的模块
- 如何在不重新加载URL的情况下查询Node.Js的后端并更新页面
- 从后端检查Open Social小工具中的用户身份验证
- 如何使用python后端和web前端提供braintree客户端令牌
- 某些Magento后端管理按钮已停止工作
- 构建一个HTML小部件来嵌入付费内容-如何确保与后端的通信安全
- 为什么Express.js后端的CORS设置不起作用
- 调用后端、多路径变量、Ext Js
- 如何断言后端端点已被调用
- AngularJS和Spring后端-在AngularJS中以user.password的形式从数据库中获取密码
- 如何将CSRF令牌从AngularJS前端发送到Spring REST服务后端
- react模板中request.js封装的fetch:如何为Spring后端处理json体中的错误
- 将支付网关与angularjs应用程序集成到spring后端
- Spring MVC AngularJS将前端与后端分开