You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS 1.5中HTTP Post请求返回404错误问题求助

搞定AngularJS 1.5 POST请求的404错误

嘿,我看了你的代码和问题描述,Postman能正常请求但Angular里返回404,大概率是请求的格式或者头信息没和服务器匹配上,咱们来一步步解决:

1. 请求头和数据格式不匹配是核心问题

你代码里有两个明显的冲突点:

  • 一开始定义了headers = {'Accept' : 'application/json'},但实际发请求时又改成了application/x-www-form-urlencoded
  • 你手动把request_data转成了JSON字符串,但却告诉服务器接受表单编码的数据,这会让服务器完全看不懂你的请求体,自然返回404了。

Postman能成功,肯定是你在Postman里发的是JSON格式的请求体,而且请求头的Content-Type设成了application/json。那咱们把Angular的代码对齐这个正确的格式:

app.factory("getResultService",['$http','$q',function($http, $q){
 var getResultApi = "https://findfalcone.herokuapp.com/find";
 var getFinalResult = function(request_data){
     // 别手动搞deferred了,$http本身就返回Promise
     return $http({
         url: getResultApi,
         method: "POST",
         data: request_data, // 直接传JS对象,$http会自动帮你转成JSON
         headers: {
             'Accept': 'application/json',
             'Content-Type': 'application/json' // 明确告诉服务器咱们发的是JSON
         }
     }).then(function (response) {
         // 直接返回数据,控制器里就能拿到response.data
         return response.data;
     }).catch(function(response) {
         // 把错误抛出去,让控制器能捕获到
         throw response.data || '请求失败啦';
     });
 };
 return {
     getFinalResult: getFinalResult
 };
}]);

2. 别再用多余的$q.defer了

Angular的$http本身就返回Promise,手动创建$q.defer属于Promise反模式,既增加代码量,还容易出错误处理的问题。上面的代码已经把这部分冗余的逻辑删掉了,直接返回$http的Promise链就行。

3. 控制器代码补个小漏洞

你的控制器最后少了一个闭合的},得补上,不然代码跑不起来:

app.controller("logicCtrl",['$scope','getDestinationService','getVehicleService','getTokenService','getResultService','$http', function($scope, getDestinationService,getVehicleService,getTokenService,getResultService,$http){
 $scope.getResult = function(){
     var resultPromise = getResultService.getFinalResult($scope.request_data);
     resultPromise.then(function(result){
         $scope.result = result; // 这里直接用result就行,工厂已经返回response.data了
         console.log("result:", $scope.result); // 用逗号打印对象更清楚
     }).catch(function(error) {
         // 加个错误捕获,方便调试哪里出问题
         console.error("请求出错了:", error);
     });
 }
}]); // 这里之前少了个},补上!

额外调试小技巧

如果改完还是有问题,打开浏览器F12的Network面板,看看你的POST请求:

  • 确认URL有没有拼写错误(别小看这个,经常踩坑)
  • 检查Request Headers里的Content-Type是不是application/json
  • 看看Request Payload是不是正确的JSON格式
  • 对比Postman里的请求头和浏览器里的,有没有差异(比如跨域问题?不过Postman能通的话,服务器应该配置了CORS,但可以看看响应头里的CORS字段)

内容的提问来源于stack exchange,提问作者Anubha Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:29:04