AngularJS POST请求数据存入data.attributes,如何改为直接存入request.body?
解决AngularJS POST请求数据存入
request.body.data.attributes的问题 看起来你的服务器端应该是配置了JSON API规范的请求解析器(比如依赖jsonapi-parser这类工具),它会自动把符合JSON API格式的请求体解析到request.body.data.attributes路径下。你的问题大概率是前端请求被自动包装成了JSON API格式,或者服务器端默认强制按这个规范解析请求。下面给你几个可行的解决方向:
1. 检查全局$http拦截器是否自动包装请求体
很多AngularJS项目会配置全局HTTP拦截器,统一把POST/PUT请求的参数包装成JSON API格式。你可以在项目的配置代码里找类似这样的逻辑:
app.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push(function() { return { request: function(config) { // 自动将POST请求体包装为JSON API结构 if (config.method === 'POST' && config.data) { config.data = { data: { attributes: config.data } }; } return config; } }; }); }]);
如果存在这样的拦截器,你可以给特定请求添加跳过标记:
// 发送请求时,在headers里添加自定义标记 $http.post(`${API_URL}/member`, obj, { headers: { 'Skip-Json-Api-Wrap': 'true' } }) .then((data) => { // 你的成功逻辑 $mdToast.show( $mdToast.simple() .textContent('created successfully') .hideDelay(3000) ) $route.reload() }, (error) => { })
然后修改拦截器,判断这个标记来跳过包装:
request: function(config) { // 只有当没有跳过标记时,才执行包装逻辑 if (config.method === 'POST' && config.data && !config.headers['Skip-Json-Api-Wrap']) { config.data = { data: { attributes: config.data } }; } // 记得删除自定义头,避免传到服务器 delete config.headers['Skip-Json-Api-Wrap']; return config; }
2. 强制发送原始JSON格式
如果没有全局拦截器,可能是请求头被修改导致服务器解析异常。你可以手动设置Content-Type为application/json,并手动序列化请求体:
var obj = { "username": email, "group": "team | " + designation }; $http.post(`${API_URL}/member`, JSON.stringify(obj), { headers: { 'Content-Type': 'application/json' } }) .then((data) => { $mdToast.show( $mdToast.simple() .textContent('created successfully') .hideDelay(3000) ) $route.reload() }, (error) => { })
这样能确保发送的是原始的JSON字符串,不会被AngularJS或第三方库额外包装。
3. 调整服务器端解析配置
如果上面的前端方案都无效,那说明服务器端默认强制按JSON API规范解析所有POST请求。这时候你需要修改服务器端的解析规则,比如:
- 如果用Express框架,检查是否使用了
jsonapi-parser中间件,尝试移除或针对特定路由禁用它; - 确保服务器端的JSON解析中间件(比如
express.json())是正常处理普通JSON格式的。
内容的提问来源于stack exchange,提问作者apple_92
相关产品推荐
相关产品推荐

