我正在创建一个小型论坛,我们公司的人员可以使用 aurelia 为他们想要即时销售的商品或服务发布广告。我有一个广告页面列表,工作正常,每个广告的详细信息页面都工作正常,都使用来自 api 的 get 请求。然而,当有人想在广告上添加评论时,我似乎无法获得帖子请求的工作。
@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 https://i.stack.imgur.com/dWg22.png
我们还收到以下 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 在同一个应用程序中发送发布请求,它工作正常,所有获取请求都工作正常,但由于某种原因,这篇文章引起了各种各样的问题。