使用SpringBoot的AngularJS $ http POST调用返回错误请求

时间:2016-05-10 17:26:58

标签: angularjs rest spring-boot

我想使用SpringBoot和@RestController为Angularjs创建一个用于REST API的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

我已经用邮递员测试了我的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中提供任何帮助,我花了很多时间在它上面!!!!

2 个答案:

答案 0 :(得分:0)

&#39;数据&#39;期望由$ http post是一个对象,而不是一个字符串。 尝试:

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

答案 1 :(得分:0)

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

在您的ajax请求($ http)中,您需要以此格式发送请求

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

您可以在开发人员工具网络标签中看到正在进行的值。

希望这会有所帮助。

快乐学习:)