【问题标题】:Angular2 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resourceAngular2对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2017-09-08 05:20:47
【问题描述】:

我试图发出一个简单的 POST 请求以在 .NET 中使用 API 创建一个帐户,但如标题所述,它失败并出现警告。 在 Postman(api 测试工具)中执行相同的请求会返回状态 200:好的,一切正常,数据已保存到数据库中。 但我不能在我的网络应用程序中做同样的事情,这是我的代码:

  register(){

let details = {
  Serviceurl: this.serviceUrl,
  CompanyName: this.companyName,
  CompanyFullName: this.companyFullName,
  LanguageCulture: this.languageCulture,
  IsNewUser: this.isNewUser,
  User: {
    UserName: this.userName,
    FirstName: this.firstName,
    LastName: this.lastName,
    Email: this.email,
    Password: Md5.hashStr(this.password)
  }
}

this.authService.createAccount(details)
.then((result) => {

}, (err) => {

});
}

然后是我的 authService 中的请求本身:

  createAccount(details){

return new Promise((resolve, reject) => {

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post('http://SITEADDRESS/api/IM_Customers/CreateNew', JSON.stringify(details), {headers: headers})
      .subscribe(res => {
        let data = res.json();
        resolve(data);

      }, (err) => {
        reject(err);
      });

});

}

【问题讨论】:

标签: angular http typescript post postman


【解决方案1】:

您需要在 API 项目中启用 No-Access-Control-Allow-Origin。 在 API 项目中,startup.cs:

public void Configure(IApplicationBuilder app){
    app.UseCors(builder=>builder.AllowOrigin().AllowAnyMethod().AllowAnyHeader());
}

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 2016-02-23
    • 2018-05-06
    • 1970-01-01
    • 2017-11-11
    • 2017-04-09
    • 2017-10-10
    • 2020-12-07
    相关资源
    最近更新 更多