在 angularjs + Spark 单页应用程序中 POST'ing JSON 时出现错误 400

Error 400 when POST'ing JSON in angularjs + Spark Single Page Application

我是单页应用领域的新手,我尝试使用 angularjs 和 Spark 框架开发应用程序。当我想从我的网站 post JSON 时收到错误 400 错误请求。这是来自客户端的代码片段:

app.controller('PostTripCtrl', function($scope, $http) {
$scope.newTrip = {};
$scope.submitForm = function() {
    $http({
        method : 'POST',
        url : 'http://localhost:4567/trips/add',
        data : $scope.newTrip,
        headers : {
            'Content-Type' : 'application/x-www-form-urlencoded'
        }
    }).success(function(data) {
        console.log("ok");
    }).error(function(data) {
        console.log("error");
        console.log($scope.newTrip);
    });

};
});    

要分配给 newTrip 的值从 html 文件中的适当输入读取。这是服务器端片段:

post("/trips/add", (req, res) -> {
        String tripOwner = req.queryParams("tripOwner");
        String startDate = req.queryParams("startDate");
        String startingPlace = req.queryParams("startingPlace");
        String tripDestination = req.queryParams("tripDestination");
        int tripPrice = Integer.parseInt(req.queryParams("tripPrice"));
        int maxNumberOfSeats = Integer.parseInt(req.queryParams("maxNumberOfSeats"));
        int seatsAlreadyOccupied = Integer.parseInt(req.queryParams("seatsAlreadyOccupied"));

        tripService.createTrip(tripOwner, startDate, startingPlace, tripDestination, tripPrice, maxNumberOfSeats,
                seatsAlreadyOccupied);
        res.status(201);
        return null;

    } , json());

最后我收到错误 400 错误请求。当我想在控制台上看到输出时,这对我来说很奇怪

System.out.println(req.queryParams());

我得到 json 个对象数组,这些对象的值是我在网站上写的。但是,当我想看到这样的输出时

System.out.println(req.queryParams("tripOwner"));

我得到空值。有人知道这里出了什么问题吗?

我建议使用 postman 向您的服务器 post 发送请求,看看它是否有效。也尝试不同的内容类型。尝试使用 curl 并使用您发送的各种 headers。 400 表示正在发送错误的数据或缺少预期数据或数据类型错误但根据您提供的代码我看不出有什么问题(但请参见下文)。

当您的服务器收到一个请求时,记录所有收到的请求 headers 并查看更改它们会发生什么。如果它在 postman 中有效,那么您可以更改您的客户端代码以反映 headers postman 正在使用。

您的 Spark 服务器是否会在您的控制器代码被命中之前验证正在发送的数据?如果是,请确保您遵守所有验证规则

再次查看您的代码时,您的客户端正在发送 post 数据中的数据,但您的服务器期望查询字符串中的数据而不是 post 数据中的数据?

如果您的服务器只发送 201 响应而不做任何其他操作,会发生什么情况?您的客户会收到 201 回复吗?如果是这样,则表明连接正常,但在您 return a 201 之前的代码有问题,请慢慢构建以解决此问题。

我认为主要问题是您使用 'Content-Type' : 'application/x-www-form-urlencoded' header 将数据发送到您的 Spark 网络服务。尝试将其作为 'Content-Type' : 'application/json' 发送,然后在您的 Java 代码中声明一个字符串以接收 req.body(),您将在其中看到所有数据。

注意:当您尝试像这样访问您的数据时 req.queryParams("tripOwner"); 您没有访问 post 数据,但您正在寻找一个名为 tripOwner 的获取参数,一个可以发送的参数像这样 http://localhost:8080/trips/add?tripOwner=MyValue.

好的,我设法用另一种方法解决了这个问题。根据 Spark 文档,我使用了 Jackson 和 ObjectMapper。感谢您的回答。

您可以在此处查看更多相关信息:https://sparktutorials.github.io/2015/04/03/spark-lombok-jackson-reduce-boilerplate.html

您可能只需要在您的 Spark 服务器中启用 CORS(跨源资源共享),这将允许您访问请求的原始域之外的 REST 资源。

    Spark.options("/*", (request,response)->{

    String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
        if (accessControlRequestHeaders != null) {
            response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
        }

    String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
        if(accessControlRequestMethod != null){
            response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
        }

    return "OK";
});

Spark.before((request,response)->{
    response.header("Access-Control-Allow-Origin", "*");
});

阅读有关预检请求的更多信息here