【问题标题】:Response is null after Http POST request in angular 7角度 7 中的 Http POST 请求后响应为空
【发布时间】:2019-05-21 11:25:57
【问题描述】:

我正在尝试将两个数据发送到我在 glassfish 上运行的 RESTful 服务器。用户必须在数据列表中选择一家餐厅。我想发送餐厅的 ID 和名称。使用 console.log 我可以打印出 id 和 name 的值,但我的响应返回 null。知道为什么会发生这种情况以及如何解决吗?

ts 文件

export class OrganizeComponent implements OnInit {

  public codeValue: string;

  codeList = [
    { id: 1, name: 'Mcdonalds' },
    { id: 2, name: 'Kentucky Fried Chicken' },
    { id: 3, name: 'Burger King' },
    { id: 4, name: 'Domino`s pizza' },
    { id: 5, name: 'New York Pizza' }
  ];


  @ViewChild('f') form: NgForm;
  restaurant = {
    id: 0,
    name: ''
  };



  constructor(private http: HttpClient) {
  }

  ngOnInit() {
  }

  public saveCode(e): void {
    let name = e.target.value;
    let list = this.codeList.filter(x => x.name === name)[0];
    // console.log(list.id);
    // console.log(list.name)


    this.restaurant.id =  list.id;
    this.restaurant.name = list.name;

console.log(list.id);
console.log(list.name);

    this.http.post('http://localhost:8080/aquadine-jee/resources/restaurant', {
      id: list.id,
      name: list.name
    })


      .subscribe( // subscribe to observable http.post
        res => {
          console.log("response" + " " + res); // log results otherwise log error
        },
        err => {
          console.log('Error occured');
        }
      );

HTML 文件

<label for="codes">Choose a restaurant:</label>
    <form
      (ngSubmit)="onOrganize(f)"
      #f="ngForm">
      <input type="text"  list="codes"  [(ngModel)]=codeValue [ngModelOptions]="{standalone: true}" (change)="saveCode($event)">
      <datalist id="codes">
        <option *ngFor="let c of codeList" [value]="c.name" >{{c.name}}</option>
      </datalist>
    </form>

后端代码:

@Stateless
@Path("restaurant")
public class RestaurantResource {

    @Inject
    private RepositoryService repositoryService;

    @GET
    @Path("restaurant")
    @Produces("application/json")
    public Response all(){
        List<Restaurant> all = repositoryService.getAllRestaurants();
        return Response
                .status(200)
                .header("Access-Control-Allow-Origin", "*")
                .entity(all)
                .build();
    }


    @GET
    @Produces("application/json")
    public List<Restaurant> getAllRestaurants(){
        return repositoryService.getAllRestaurants();

    }

    @POST
    @Consumes("application/json")
    public Response save(Restaurant restaurant){
        repositoryService.save(restaurant);
        return Response
                .status(201)
                .build();
    }
public class Restaurant {

    @Id
    @Column(name="idRestaurant")
    @NotBlank
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;



    public Restaurant(Integer id,Integer restaurantId , String naam) {
        this.id = id;
        this.restaurantId = restaurantId;
        this.naam = naam;
    }

后端服务出错:

内部服务器错误 500。 在 EJB RepositoryService 上调用,方法:public void nl.aquadine.service.RepositoryService.save(nl.aquadine.model.Restaurant)]] 和 javax.ejb.TransactionRolledbackLocalException:抛出异常 来自 bean 和引起:org.hibernate.PersistentObjectException: 分离实体传递给坚持:nl.aquadine.model.Restaurant at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124) 在 org.hibernate.event.internal.DefaultPersis 等处。

【问题讨论】:

  • 如果响应为空,您必须在后端检查那里发生了什么。您必须调试后端,而不是前端(Angular 应用程序)。
  • 如果您的目标是通过 JSON 发送,那么您缺少正确的标头
  • @jcuypers Angular Http 客户端设置 json 帖子的标题。这是这个库的默认行为。更多信息:angular.io/guide/http#making-a-post-request
  • 我添加了一些后端代码。我似乎找不到错误
  • @ChristianBenseler 我看不出在哪里可以找到默认行为。它没有写在任何地方,示例还指定了标题。英雄示例定义了一些基本的标头,每次调用都包含这些标头。这不是默认行为

标签: angular rest http glassfish


【解决方案1】:

将以下内容添加到您的代码中

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};

const data = {
   id: list.id,
   name: list.name
};

  this.http.post('http://localhost:8080/aquadine-jee/resources/restaurant', 
      JSON.stringify(data), httpOptions)

【讨论】:

  • 另一点可能是您需要正确的 CORS 策略,以便您可以接受这种飞行前类型的请求。这意味着您愿意接受 OPTIONS 方法,除了 GET / POST (这是邮递员不会生成的顺便说一句...... OPTIONS/204)
  • 当我现在使用 http post 动词时,我总是得到一个内部服务器错误 500 与旧代码和新代码。我在其他评论中添加了错误
  • ok 暂时删除保存方法,看看你得到了什么。尝试转储变量以查看它们是否存在
【解决方案2】:
  1. 首先使用 POSTMAN 或任何其他费用测试您的后端响应,如果它工作正常,那么您可以专注于前端。

【讨论】:

  • 是和不是。邮递员没有正确模拟飞行前的行为,这应该是一个评论。不是答案
猜你喜欢
  • 1970-01-01
  • 2020-11-17
  • 2019-10-21
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多