【问题标题】:angular2 "400 Bad Request" on POST RequestPOST 请求上的 angular2“400 错误请求”
【发布时间】:2017-12-24 17:06:33
【问题描述】:

当我执行 POST 时,我收到错误 POST http://localhost:5000/api/activities 400 (Bad Request) 但是当我添加一个 id 时,我的 put 效果很好。

谁能帮帮我,我找不到解决办法。为什么会收到 400(错误请求)错误?

这是我的代码:

在全球范围内:

BASE_URL_API = 'http://localhost:5000/api/'

在activitiy.service.ts中

private activitiesUrl = this.globals.BASE_URL_API + 'activities';

//POST
private post(activity: Activity): Promise<Activity> {
let headers = new Headers({
  'Content-Type': 'application/json'
});

return this.http
  .post(this.activitiesUrl, JSON.stringify(activity), { headers: headers })
  .toPromise()
  .then(res => res.json().data)
  .catch(this.handleError);
 }
// Update existing Activity
private put(activity: Activity): Promise<Activity> {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');

  let url = `${this.activitiesUrl}/${activity.id}`;

  return this.http
    .put(url, JSON.stringify(activity), { headers: headers })
    .toPromise()
    .then(() => activity)
    .catch(this.handleError);
}

在 addActivity.ts 中

activityCredentials = {
id: null,
name: 'test', 
description: 'test description',
locationId: 2,
activityTypeId: 2,
};

... 

public save(){
    this.activityService.save(this.activityCredentials).then(success => {
     if (success) {
        this.createSuccess = true;
          this.showPopup("Success", "Activity added.");
      } else {
        this.showPopup("Error", "Problem adding activities.");
      }
    },
    error => {
      this.showPopup("Error", error);
    });
  } 

在 ASP.NET API 中

[HttpPost(Name = "CreateActivity")]
    public async Task<IActionResult> CreateActivity([FromBody] Activity item)
       {
           if(item == null)
           {
               return BadRequest();
           }

          ApplicationDbContext.Activities.Add(item);
           await ApplicationDbContext.SaveChangesAsync();

           return this.CreatedAtRoute("GetActivityById", new { Controller = "ActivitiesController", activityId = item.Id }, item);
       }

       [HttpPut("{activityId:int}", Name = "UpdateActivity")]
       public async Task<IActionResult> UpdateActivity(Int16 activityId, [FromBody] Activity item)
       {
           if(item == null || item.Id != activityId)
           {
               return BadRequest();
           }

           var model = await ApplicationDbContext.Activities.FirstOrDefaultAsync(o => o.Id == activityId);

           if(model == null)
           {
               var msg = String.Format(FAILGETENTITYBYID, activityId);
               return NotFound(msg);
           }

           model.Name = item.Name;
           model.Description = item.Description;
           model.LocationId = item.LocationId;
           model.ActivityTypeId = item.ActivityTypeId;

           ApplicationDbContext.Activities.Attach(model);
           ApplicationDbContext.Entry(model).State = EntityState.Modified;
           await ApplicationDbContext.SaveChangesAsync();

           return new NoContentResult();
       }

我不明白这个问题。有人可以帮帮我吗?

【问题讨论】:

  • 检查 JSON.stringify(activity) 对象是否传递参数
  • @Vignesh JSON.stringify(activity) 正在传递参数的
  • 你发送的是小写的is,而在服务器上你使用大写的i访问Id。请检查是否是问题所在。
  • @AlexFlorin 我已经更改了它,但它仍然无法正常工作。当我在我的请求中添加一个 id 时,它与 put 完美配合。所以我认为这不是参数的问题吗?
  • 400 (Bad Request) 意味着您的请求甚至不会离开客户端应用程序。也许您可以调查.post() 方法背后发生的事情,或者使用activity 对象上的console.log() 更新您的问题。另外,据我所知,没有必要对它进行 srtingify。您是否尝试过直接发送活动对象? (没有JSON.stringify() 电话)。

标签: asp.net-mvc angular


【解决方案1】:

我试图复制您的问题,这是最终结果:

  • 这里是活动服务:

import { Http, RequestOptionsArgs, Headers } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs';

class Activity {
  id: null;
  name: string;
  description: string;
  locationId: number;
  activityTypeId: number;
};

@Injectable()
export class ActivitiesService {
  private activitiesUrl = 'http://ask-around.ngenh.com:6543/api/auth';

  constructor(
    private http: Http
  ) { }

  //POST
  public post(activity: Activity): Promise<Activity> {
    let headers = new Headers({
      'Content-Type': 'application/json'
    });
    let url = this.activitiesUrl + '/login';

    return this.http
      .post(url, activity, { headers: headers })
      .toPromise()
      .then(res => {
        console.log(res);
        return res.json().data
      })
      .catch(this.handleError);
   }

  // Update existing Activity
  public put(activity: Activity): Promise<Activity> {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let url = `${this.activitiesUrl}/${activity.id}`;

    return this.http
      .put(url, activity, { headers: headers })
      .toPromise()
      .then(res => {
        console.log(res);
        return res.json().data
      })
      .catch(this.handleError);
  }

  handleError(err) {
    console.log(err);
  }
}

然后您只需将它提供到一个模块中并像使用任何其他服务一样使用它。我提供的链接是我的公共 API,您可以看到它返回 500 Internal server error,因为它无法处理输入。

观察:

  • 您的 postput 方法是私有的(这不会影响任何事情)
  • 提供给then 方法的箭头函数不同

除此之外,我想不出还有什么可能给您带来麻烦。如果仍然无法正常工作,请尝试在 plunker 或类似名称中复制问题,然后用它更新您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多