[英]angular2 “400 Bad Request” on POST Request
當我執行POST時,出現錯誤POST http:// localhost:5000 / api / activities 400(錯誤請求),但是當我添加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();
}
我沒問題。 有人可以幫我嗎?
我試圖復制您的問題,這是最終結果:
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
因為它無法處理輸入。
觀察:
post
和put
方法是私有的(這不會影響任何內容) then
方法提供的箭頭功能不同 除此之外,我想不出其他任何可能給您造成麻煩的問題。 如果仍然無法解決問題,請嘗試用插塞式類似工具復制該問題,然后使用該問題更新您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.