【问题标题】:How to pass String in POST request from AngularJS to Http Servlet?如何将 POST 请求中的字符串从 AngularJS 传递到 Http Servlet?
【发布时间】:2014-09-17 18:19:23
【问题描述】:

这是我的 Angular 代码(获取请求工作正常,但不是发布请求。我在 Servlet 端的 carrier_id 中收到 null)。

app.js

var app = angular.module( "admin" , []);


app.config(function ($httpProvider){
    // set the Content-Type header globally
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// define ajax call behavior globally
// set up global transformRequest function
$httpProvider.defaults.transformRequest = function(data){

    if (data === undefined) {
        return data;
    }
    return $.param(data);
};})

app.controller('mainController', function($scope, $http, $window){

$scope.fileList =[];
$scope.selectedFile = null;
$http({
    method: 'GET',
    url :'hrp/filelist' 
}).success( function(data,status,headers,config){ 
    data.file_list.splice(0, 1) // to remove header row
    $scope.fileList=data.file_list

}).error(function(){
    alert("error")
})
$scope.submitFile = function(selectedFile){
    console.log("happy" + selectedFile);
    $http({
        method: 'POST',
        url: 'hrp/carrierInfo',
        data: {carrier_id: selectedFile}
    }).success(function(data){
        alert(data.carrier_id + " & " + data.method_name)
    }).error(function(){
        alert("errors")
    })
}});

以及部分 Servlet 代码:

String carrier_id = (String)request.getAttribute("carrier_id");

response.setContentType("application/json");

但它是空的。

【问题讨论】:

  • 您发送的内容类型是 application/json 还是 form-encoded?
  • 是的,response.setContentType("application/json");

标签: angularjs servlets


【解决方案1】:

您可能需要设置内容类型:

试试form-urlencoded

$http({
    method: 'POST',
    url: 'hrp/carrierInfo',
    data: {carrier_id: selectedFile},
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}).then(function(result) {
       console.log(result);
   }, function(error) {
       console.log(error);
   });

并尝试应用程序/json

$http({
    method: 'POST',
    url: 'hrp/carrierInfo',
    data: {carrier_id: selectedFile},
    headers: {
        'Content-Type': 'application/json'
    }
}).then(function(result) {
       console.log(result);
   }, function(error) {
       console.log(error);
   });

查看服务器是否得到不同的结果

【讨论】:

  • 但我猜这是在代码顶部提到的 app.config($httpProvider){} 中完成的,而且我尝试添加标题
  • 好的,在您的服务器上,您可以抓取整个发布请求并查看收到的内容吗?意思是,你能遍历请求吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
  • 2011-09-17
相关资源
最近更新 更多