Aurelia Post使用http-fetch-client生成选项请求

时间:2016-06-20 17:38:26

标签: api post cors options aurelia

我正在建立一个小型论坛,让我们公司的人们可以使用aurelia为他们想要出售的商品或服务提供广告。我有一个广告页面列表工作正常,每个广告的详细信息页面都使用来自api的get请求。但是当有人想要在广告上添加评论时,我似乎无法获得Post所要求的作品。

@inject(HttpClient)
export class ApiData {
    constructor(httpClient) {
        httpClient.configure(config => {
            config
                .withBaseUrl("MyUrl");
        });
        this.http = httpClient;
        //.configure(x => {x.withHeader('Content-Type', 'application/json');});
    }

    postAdvertComment(comment, id) {
        return this.http.fetch(`/adverts/${id}/comments`, {
            method: "post",
            body: json(comment),
            headers: {
                'Accept': 'application/json'
            }
        });
    } 

    getAdverts() {
        return this.http.fetch("/adverts")
            .then(response => {
                return this.adverts = response.json();
            });
    }

    getAdvert(id) {
        return this.http.fetch(`/adverts/${id}`)
            .then(response => {
                return this.advert = response.json();
            });
    }
}

执行此项目我们在CORS中遇到了一些问题,所有问题都通过在api中添加AllowCors标记来解决,包括所有方法等。

<add key="CorsAllowedOrigins" value="*" />
<add key="CorsAllowedHeaders" value="" />
<add key="CorsAllowedMethods" value="*" />

然而,当我尝试运行帖子时,它运行一个选项方法并返回400 Bad请求。 Here

我们还收到以下CORS错误:

Fetch API cannot load MyURL/api/adverts/2/comments. Response to preflight
request doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'http://localhost:49877' is 
therefore not allowed access. The response had HTTP status code 400. If an 
opaque response serves your needs, set the request's mode to 'no-cors' to fetch 
the resource with CORS disabled.

我不知道我们的c#api是否存在问题,或者我是如何尝试从aurelia发帖的,但是我们已经尝试过发送邮递员的请求并且工作正常,尝试发送使用jquery在同一个应用程序中发布请求,它工作正常,所有get请求都可以正常工作,但由于某种原因,这篇文章引发了各种各样的问题。

1 个答案:

答案 0 :(得分:2)

这似乎是您的WebAPI中的一个问题,但在给您一些可能的解决方案之前,我想向您展示一些重要的事情。

  • 邮递员不受CORS影响,因此所有请求都有效。
  • jQuery ajax使用XHR(XmlHttpRequest对象)而aurelia-fetch-client使用fetch(window.fetch。但是,fetch-polyfill在后台使用XHR)。他们是 解决同一问题的不同方法。仅仅因为其中一个工作,实际上并不意味着另一个也应该工作。
  • OPTIONS请求是由fetch生成的,它的工作原理。更多信息请访问https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en

要解决此问题,请尝试从web.config中删除这些标记,并在Startup.cs中允许使用CORS。像这样:

public void Configuration(IAppBuilder app)
{
    app.UseCors(CorsOptions.AllowAll); //or another parameter
    //rest of your code
}

您不必将content-type标头设置为application / json。当您使用json()函数---&gt;时自动生成body: json(comment)

如果您使用的是OWIN,则可能需要将内容类型发送为x-www-form-urlenconded。在这种情况下,请查看此Post 'x-www-form-urlencoded' content with aurelia-fetch-client