【问题标题】:How to pass the headers separatelyin angular4(when passing json object to API not working)如何在角度 4 中分别传递标头(将 json 对象传递给 API 时不起作用)
【发布时间】:2019-09-18 03:56:27
【问题描述】:

在这里,我正在尝试使用 Angular 4 捕获一些数据并将其保存到 DB(发布方法)。当单击确认按钮时出现类似 CORS 策略阻止的错误:对预检请求的响应不' t 通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

当我尝试邮递员时,我得到了输出。所以我确认我的 Web APi 工作正常。实际上我是角度方面的新手,所以我认为我的问题在于打字稿或角度服务。我想要这样的输出。

 { 
"Header": {

            "UserID": 6,
           "created": "February 4, 2016 10:13:00",
            ....etc........
         },

  "detail": [
    {

      "ShopID": 1,
     "ItemID": 126,
    .....etc.........
   },
  {     
  "ShopID": 1,
   "ItemID": 127,
   .....etc.........
    }
  ]
 }

这是我的打字稿文件

 stockitems: IStockCountHeaders[] = [];   
 items: IStockCountHeaders;
  stockdetail: IStockdetails[] = [];

  addItems(value: any) {
this.items = new IStockCountHeaders(this.userid, this.created, t this.confirm,this.shopid, 
 value.ItemID, value.PackingTypeID, value.ItemCode, value.ItemDescription, 
 value.PackingtypeName, 
    value.Stock,
   );
this.stockitems.push(this.items);
  }
onclick(){
 this._enqService.CatchStockDetailHeader(this.stockitems)
    .subscribe(value => {
        if (typeof value !== 'undefined' && value != null) {
            value.forEach(items => {
                this.stockitems.push(this.items)
            });
        }
    },
        error => {
            console.error(error);
            this.statusMessage = "Problem with the service.Please try again after sometime";
        });
 }

这是我的 angularservice.ts 文件

      CatchStockDetailHeader(stock: any)
    : Observable<IStockCountHeaders[]> {
    let IStockCounts = stock;  
    console.log(IStockCounts)
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    headers.append('userid', IStockCounts.userid);
    headers.append('created', IStockCounts.created);
    headers.append('.CompanyID', IStockCounts.CompanyID);
    headers.append('modified', IStockCounts.modified);
    headers.append('modifieduserid', IStockCounts.modifieduserid);
    headers.append('confirm', IStockCounts.confirm);    
    return this._http.post('http://localhost:3071/api/Stockcountheader/' + 'Stock', IStockCounts, options)
        .map((response: Response) => <IStockCountHeaders[]>response.json())
        .catch(this.handleError);
}

startup.cs 文件

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WebAPIService.Startup))]

namespace WebAPIService
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);

}
}
}

我的 API

    public class StockClass
{
    public spGetNewStockCountHeader_Result header { get; set; }
    public List<spGetNewStockCountDetails_Result> detail { get; set; }

}

public class StockcountheaderController : ApiController
{
    private adminv2Entities enqentities = new adminv2Entities();
    HttpSessionState session = HttpContext.Current.Session;
    [HttpPost]
    public IHttpActionResult Stock([FromBody] StockClass obj)
    {

        spGetNewStockCountHeader_Result stockheader = new spGetNewStockCountHeader_Result();
        int schid = enqentities.spGetNewStockCountHeader(obj.header.UserID, obj.header.created, obj.header.CompanyID, obj.header.modified, obj.header.modifieduserid, obj.header.confirm, obj.header.ShopId).FirstOrDefault().Schid;

        foreach (var Stockobject in obj.detail)
        {
            enqentities.spGetNewStockCountDetails(Stockobject.ShopID, Stockobject.ItemID, Stockobject.PackingTypeID, Stockobject.Itemcode, Stockobject.Itemdescription, Stockobject.PackingtypeName, Stockobject.Stockcount, schid);
        }
        return Ok();
    }



        public StockClass getStock()
    {
        StockClass obj = new StockClass();
        spGetNewStockCountHeader_Result tmphd = new spGetNewStockCountHeader_Result();
             obj.header = tmphd;
        List<spGetNewStockCountDetails_Result> tmplist = new List<spGetNewStockCountDetails_Result>();
        spGetNewStockCountDetails_Result tmp = new spGetNewStockCountDetails_Result();
           tmplist.Add(tmp);
        obj.detail = tmplist;
             return obj;
    }

【问题讨论】:

  • 允许来自您的资源的 CORS。该错误正是在说明您需要做什么。转到您正在访问的 API 并允许来自后端的 CORS
  • @Nandan 我怎样才能分配 cors?
  • 您使用的是哪个后端?可以分享一下 API sn-p
  • @Nandan Web API(实体框架)
  • 你能分享我/api/Stockcountheader/代码

标签: angular typescript angular-services angular4-httpclient angular-json


【解决方案1】:

转到您的 startup.cs 文件并将其添加到您的 Configure 方法中。

app.UseCors(options =&gt; options.AllowAnyOrigin());

之后编辑您的ConfigureServices 方法:-

services.AddCors(c =>  
 {  
    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());  
 });

现在尝试运行您的应用程序

【讨论】:

  • 应该没问题..请用上面的代码编辑你的startup.cs,然后再次检查是否存在其他错误。
  • 这是我的 startup.cs 文件命名空间 WebAPIService { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } }
  • 我的意思是用 startup.cs 代码更新你的问题
【解决方案2】:

在您的 WebApiConfig 中包含 EnableCors,这应该可以工作

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

更多参考请见:https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

【讨论】:

【解决方案3】:

在你的 webApiConfig 中添加这一行

var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);

会有用的

如果您需要在 Angular 中添加标题,您可以参考以下代码:-

let httpOptions = new HttpHeaders() ; 
                     .set('Access-Control-Allow-origin','*')

将这些 httpOptions 发送到 post ,获取您正在发出的请求

在您的代码中您也可以这样做:- 用这个替换标题行

let headers = new HttpHeaders({'Content-Type':'application/json','Access-Control-Allow-Origin':'*'})

【讨论】:

  • @BrockJames 这是服务器端问题,您不需要在 Angular 中添加任何代码
  • 你检查我的角码吗?如果有什么问题吗?
  • 得到错误严重性代码描述项目文件行抑制状态错误CS0144无法创建抽象类或接口'HttpHeaders'的实例
  • @BrockJames 您是否也在 webapi 中添加了上述代码?作为其主要的服务器端问题
猜你喜欢
  • 1970-01-01
  • 2012-06-02
  • 2019-07-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
相关资源
最近更新 更多