简体   繁体   English

使用Angular 2将数据发布到Asp.net Web API

[英]Post data to Asp.net web api using Angular 2

I want to post data on my asp.net web api using angular 2 but i am getting these errors. 我想使用angular 2在asp.net Web API上发布数据,但出现这些错误。 I cannot figure out what is wrong with my code. 我无法弄清楚我的代码出了什么问题。 错误截图

Asp.net Code ASP.NET代码

    [ResponseType(typeof(User))]
    public IHttpActionResult PostUser(User user)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Users.Add(user);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = user.UserID }, user);
    }

Angular 2 code Angular 2代码

////////////////////////////////////////////////////////// Service /////////////////////////////////////////////////////////// ///////////////////////////////////////////////////// /////////服务/////////////////////////////////////////// //////////////////

@Injectable()
export class TaskService {

  private Url = 'https://jsonplaceholder.typicode.com/posts';

  private handleError(error: any): Promise<any> {
    debugger;
  console.error('An error occurred', error); // for demo purposes only
  return Promise.reject(error.message || error);
}
  task;

  constructor( private _http : Http) {
  }

  getItems()
  {
     var Promise =this._http.get(
      'http://localhost:27353/api/Users')
      .map(res=>res.json())
      .toPromise()
    Promise.then(taskFromServer => this.task = taskFromServer)
    Promise.catch(this.handleError)
  }

  postitems(userId,username,userrole)
  {
      debugger;
      let data = {
        "UserName": username,
        "UserRole": userrole

      }
    //let body = JSON.stringify(data);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

  return this._http
    .post('http://localhost:27353/api/Users', JSON.stringify(data), {headers: headers})
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);
}

private extractData(res: Response) {
  let body = res.json();
  return body.data || { };
}  

}

///////////////////////////////////////////////Task Component /////////////////////////////////////////////////////
@Component({

  selector: 'tasks',
  providers: [TaskService],
  template: `<h4> This is the Task in Angular </h4>
  <Button class = "btn btn-primary"  (click) = "OnClick()" > Click me </Button>


  <input [(ngModel)] = "userId" >
  <input [(ngModel)] = "username" >
  <input [(ngModel)] = "userrole" >

   <Button class = "btn btn-primary"  (click) = "OnClick(userId,username,userrole)" > Submit </Button>

<div class="table-responsive" >


<table class="table" style="width:100%">
  <tr>
    <th>ID</th>
    <th>Title</th> 
    <th>Body</th>
  </tr>

<tr *ngFor = "let task of tasklist.task">
    <td>{{task.UserID}}</td>
    <td>{{task.UserName}}</td> 
    <td>{{task.body}}</td>
    <td> <a class="btn btn-link" (click) = Edit(task) > Edit </a> </td>
  </tr>

 </table>

</div>

  `
})

export class TasksComponent implements OnInit {

  sample:string = ""

  constructor(public tasklist: TaskService , private router: Router) { }  

  ngOnInit() {

    this.tasklist.getItems(); 

  }

  OnClick(userId,username,userrole)
  {
    debugger;
    this.tasklist.postitems(userId,username,userrole);
  }

  Edit(value)
  {
    debugger;
    this.router.navigate(['/others' , value]);
  }
}

The OPTIONS verb is probably from a cross-domain JavaScript request done by your browser. OPTIONS动词可能来自浏览器完成的跨域JavaScript请求。 The OPTIONS is part of a pre-flight request the browser carries out to find out what is supported for cross-domain requests. 选项是飞行前请求的一部分,浏览器执行该请求以查找跨域请求支持的内容。

Try making the same POST from the Chrome extension Postman. 尝试通过Chrome扩展程序Postman进行相同的POST。 As an extension to Chrome it does not follow the same CORS rules. 作为Chrome的扩展程序,它不遵循相同的CORS规则。 If it works in Postman then this is a CORS issue and you need to enable CORS. 如果它在Postman中工作,则这是CORS问题,您需要启用CORS。

Follow the instructions here: https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors . 请按照以下说明进行操作: https : //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM