angular2“400错误的请求”在POST请求
问题描述:
当我做一个职位,我得到的错误POST http://localhost:5000/api/activities 400(错误请求) 但是当我添加一个ID我放完美的作品。angular2“400错误的请求”在POST请求
有人可以帮我,我没有找到解决办法。为什么我会收到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();
}
我不明白为什么。有人可以帮我吗?
答
我试图复制你的问题,这是最终的结果:
- 这里是ActivitiesService:
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
方法箭头功能是与此不同
其他,我想不出任何可能给你带来麻烦的事情。如果仍然无效,请尝试复制类似的plunker什么问题,然后用它更新你的问题。
检查JSON.stringify(activity)对象是否传递param's – Vignesh
@Vignesh JSON.stringify(activity)正在传递param's –
您在发送小写'is',而在服务器*问'Id'时大写字母i。请检查是否是这个问题。 –