【问题标题】:AngularJS $http POST calls with SpringBoot return bad request使用 SpringBoot 的 AngularJS $http POST 调用返回错误请求
【发布时间】:2016-05-10 17:26:58
【问题描述】:

我想使用 SpringBoot 和 @RestController 为 REST api 创建一个带有 Angularjs 的 Web 客户端 这是实体产品:

package com.agTest.entities;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long idProduct;
    private String description;
    private double prix;


    public Product() {
        super();
        // TODO Auto-generated constructor stub
    }


    public Product(String description, double prix) {
        super();
        this.description = description;
        this.prix = prix;
    }


    public Long getIdProduct() {
        return idProduct;
    }
    public void setIdProduct(Long idProduct) {
        this.idProduct = idProduct;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public double getPrix() {
        return prix;
    }
    public void setPrix(double prix) {
        this.prix = prix;
    }

}

这是我使用 JpaRepository 的 ProductRepository 接口:

package com.agTest.Dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.agTest.entities.Product;

public interface ProductRepository extends JpaRepository<Product, Long>{

}

这是我的 ProductMetier 界面:

package com.agTest.services;

import java.util.List;

import com.agTest.entities.Product;

public interface ProductMetier {
    public Product saveProduct(Product p);
    public List<Product> getProducts();

}

这是我的 ProductMetierImpl 类:

package com.agTest.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.agTest.Dao.ProductRepository;
import com.agTest.entities.Product;
@Service
public class ProductMetierImpl implements ProductMetier{

    @Autowired
    private ProductRepository productRepository; 
    @Override
    public Product saveProduct(Product p) {
        productRepository.save(p);
        return p;
    }

    @Override
    public List<Product> getProducts() {

        return productRepository.findAll();
    }

}

这是我的@RestController 类:

package com.agTest.RestServices;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.agTest.entities.Product;
import com.agTest.services.ProductMetier;

@RestController
public class ProductRestService {

    @Autowired
    private ProductMetier productMetier;

    @RequestMapping(value="/products", method=RequestMethod.POST)
    public Product saveProduct(@RequestBody Product p){
        return productMetier.saveProduct(p);
    }

    @RequestMapping(value="/products", method=RequestMethod.GET)
    public List<Product> getProducts(){
        return productMetier.getProducts();
    }

}

这是我的 application.properties:

# Datasource settings:
spring.datasource.url = jdbc:mysql://localhost:3306/agence_test
spring.datasource.username = root
spring.datasource.password =
spring.datasource.driver-class-name = com.mysql.jdbc.Driver

spring.jpa.database = MYSQL

spring.jpa.show-sql = true

spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

我已经用 postman 测试了我的 api,一切都很顺利,但是当我尝试创建 angularjs 客户端时,http Post 方法返回异常:

这是我的 angularjs 控制器:

var app=angular.module("AVG",[]);
app.controller("AVGController",function($scope,$http){

    $scope.products=[];
    $scope.description=null;
    $scope.prix=null;

    $scope.getProducts= function(){

        $http.get("/products")
        .success(function(data){
            $scope.products=data;
        })
        .error(function(data){
            alert("error");
        });

    };
    // headers :{'Content-Type':'application/json'}
    $scope.saveMembre= function(){
        $http({
                method : 'POST',
                url    : "/products",
                data   : "description="+$scope.description+"prix="+$scope.prix,
                headers :{'Content-Type':'application/json'}


        })
        .success(function(data){
            alert("success");
         })
         .error(function(data){
                alert("error");
            });


    };



});

这是我的 index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" type="text/css" href=""bootstrap-3.3.6-dist/css/bootstrap.min.css""/>
<title>Agence Test</title>
</head>
<body ng-app="AVG" ng-controller="AVGController">
  <h1>AVE.com</h1>
    <!-- Sauvegarde des Membres -->
  <div>

  <form>
   <label>Description</label>
   <input type="text"  ng-model="description"/>
   <label>Prix</label>
   <input type="text"  ng-model="prix"/>
   <button ng-click="saveMembre()"> SAVE </button>
   </form>

  </div>



  <!-- Affichage des Membres -->
   <div >
    <button type="button" ng-click="getProducts()">Get Products</button>
    <table>
    <tr>
    <th>ID</th> <th>DESCRIPTION</th> <th>PRIX</th>
    </tr>
    <tr ng-repeat="item in products"> 
    <td>{{item.idProduct}}</td>
    <td>{{item.description}}</td>
    <td>{{item.prix}}</td>
    </tr>
    </table>
   <!--  <ul>
       <li ng-repeat="item in membres"> {{item.idMembre}}</li>
       <li ng-repeat="item in membres"> {{item.nomMembre}}</li>
    </ul> -->
</div>

  <script type="text/javascript" src="angular/angular.min.js"></script>
   <script type="text/javascript" src="js/app.js"></script>

</body>
</html>

这里是调用http post方法时返回的异常:

Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
2016-05-10 18:03:33.978  WARN 5420 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'description': was expecting ('true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@22dbf53d; line: 1, column: 13]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'description': was expecting ('true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@22dbf53d; line: 1, column: 13]

http get 方法按预期工作

请在我的 PEF 中为我提供任何帮助,我花了很多时间在上面!!!!

【问题讨论】:

    标签: angularjs rest spring-boot


    【解决方案1】:

    $http post 所期望的“数据”是一个对象,而不是一个字符串。 试试:

    data   : {"description":$scope.description, "prix":$scope.prix}
    

    【讨论】:

    • 想蒂埃里兄弟,真的不知道怎么想你
    【解决方案2】:

    你的 spring 代码没有问题。这里唯一的问题是您的请求如何发送值

    在您的 ajax 请求 ($http) 中,您需要以这种形式发送请求

    data : {"property1":value1, "property2": value2, ....,"propertyN" : value"}
    

    您可以在开发人员工具网络选项卡中看到正在运行的值。

    希望对你有所帮助。

    快乐学习:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 2021-04-24
      相关资源
      最近更新 更多